/* rathmind — Gateway
 * Dual-hemisphere, cursor-gravity. Shared Point Field transforms between lattice + cloud.
 * Typographic mark "·" recurs. Held key reveals a personal note.
 */

const Gateway = {};

Gateway.View = function({ tweaks, onEnter }) {
  const canvasRef = React.useRef(null);
  const fieldRef = React.useRef(null);
  const [hover, setHover] = React.useState(null); // 'data' | 'mind' | null
  const [noteOpen, setNoteOpen] = React.useState(false);
  const [idle, setIdle] = React.useState(false);

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

  React.useEffect(() => {
    if (!fieldRef.current) return;
    fieldRef.current.setVariant(tweaks.throughline || 'A');
    fieldRef.current.setMotion(tweaks.motion / 100);
    fieldRef.current.setHeavy(tweaks.webgl / 100);
  }, [tweaks.throughline, tweaks.motion, tweaks.webgl]);

  // Held-key reveal
  React.useEffect(() => {
    let hold = null;
    const down = (e) => {
      if (e.key === ' ' && !hold) {
        hold = setTimeout(() => setNoteOpen(true), 900);
      }
    };
    const up = () => { if (hold) { clearTimeout(hold); hold = null; } };
    window.addEventListener('keydown', down);
    window.addEventListener('keyup', up);
    return () => { window.removeEventListener('keydown', down); window.removeEventListener('keyup', up); };
  }, []);

  // Idle detector
  React.useEffect(() => {
    let t = null;
    const bump = () => { setIdle(false); clearTimeout(t); t = setTimeout(() => setIdle(true), 9000); };
    bump();
    window.addEventListener('mousemove', bump);
    return () => { clearTimeout(t); window.removeEventListener('mousemove', bump); };
  }, []);

  const layout = tweaks.gateway || 'horizon';

  return (
    <div className="is-gateway" style={{
      position: 'relative', width: '100%', height: '100%',
      background: 'var(--paper)', color: 'var(--ink)',
      fontFamily: 'var(--sans)', overflow: 'hidden',
    }}>
      <canvas ref={canvasRef} style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
      }}/>

      {/* Chrome */}
      <header style={{
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 3,
        padding: '28px 40px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div style={{ fontFamily: 'var(--serif)', fontSize: 22, letterSpacing: '-0.01em', fontStyle: 'italic' }}>
          rath<span className="dot" style={{ background: 'currentColor', width: 5, height: 5 }}/>mind
        </div>
        <div className="num">Rathinavel D <span className="dot"/> 17+ years across data & mindfulness</div>
        <div className="num">Gateway <span className="dot"/> press <kbd style={kbdStyle()}>space</kbd> for a note</div>
      </header>

      {/* Main content */}
      {layout === 'horizon' && <HorizonLayout hover={hover} setHover={setHover} onEnter={onEnter}/>}
      {layout === 'split' && <SplitLayout hover={hover} setHover={setHover} onEnter={onEnter}/>}
      {layout === 'manifesto' && <ManifestoLayout hover={hover} setHover={setHover} onEnter={onEnter}/>}

      {/* Idle / note */}
      {idle && !noteOpen && (
        <div style={{
          position: 'absolute', bottom: 40, left: '50%', transform: 'translateX(-50%)',
          zIndex: 3, pointerEvents: 'none',
          fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.14em',
          color: 'var(--ink-3)', textTransform: 'uppercase',
          animation: 'breathe 4s ease-in-out infinite',
        }}>
          <style>{`@keyframes breathe { 0%,100% { opacity: 0.35 } 50% { opacity: 1 } }`}</style>
          the field is breathing <span className="dot"/> you can too
        </div>
      )}

      {noteOpen && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(11,11,13,0.86)',
          backdropFilter: 'blur(8px)', zIndex: 10,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          padding: 60,
        }} onClick={() => setNoteOpen(false)}>
          <div style={{ maxWidth: 620 }}>
            <div className="num" style={{ color: 'var(--ink-3)' }}>A note, from Rathinavel</div>
            <div style={{
              fontFamily: 'var(--serif)', fontSize: 36, lineHeight: 1.3,
              letterSpacing: '-0.015em', marginTop: 20, fontStyle: 'italic',
            }}>
              "The analyst who can sit with ambiguity makes better models.
              The meditator who respects evidence builds deeper practice.
              Data sharpens how we see the world; mindfulness sharpens how
              we see ourselves."
            </div>
            <div className="num" style={{ marginTop: 24 }}>— Rathinavel D <span className="dot"/> release to return</div>
          </div>
        </div>
      )}
    </div>
  );
};

function kbdStyle() {
  return {
    fontFamily: 'var(--mono)', fontSize: 10,
    padding: '2px 6px', border: '1px solid var(--rule)',
    marginLeft: 6,
  };
}

// ─── Layout A · Horizon ───────────────────────────────────────
function HorizonLayout({ hover, setHover, onEnter }) {
  return (
    <div style={{
      position: 'relative', zIndex: 2, height: '100%',
      display: 'grid', gridTemplateRows: '1fr auto 1fr',
      padding: '0 40px',
    }}>
      <div/>
      <div style={{ textAlign: 'center' }}>
        <div className="num" style={{ color: 'var(--ink-3)', marginBottom: 28 }}>
          Insight <span className="dot"/> Awareness
        </div>
        <h1 style={{
          fontFamily: 'var(--serif)', fontSize: 'clamp(68px, 9vw, 160px)',
          lineHeight: 0.92, letterSpacing: '-0.035em', margin: 0, fontWeight: 400,
        }}>
          <Motion.KineticTitle text="Precision in numbers." accent="var(--data-accent)"/>
          <br/>
          <em style={{ fontStyle: 'italic', color: 'var(--ink-3)' }}>
            <Motion.KineticTitle text="Presence in life." accent="var(--mind-accent)"/>
          </em>
        </h1>
        <p style={{
          fontFamily: 'var(--sans)', fontSize: 16, lineHeight: 1.55,
          color: 'var(--ink-2)', maxWidth: 560, margin: '32px auto 0',
        }}>
          Rathinavel D. Data &amp; analytics consultant by day, mindfulness teacher by evening. <br/>
          Choose the hemisphere you came to read.
        </p>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0,
        alignItems: 'end', paddingBottom: 56,
      }}>
        <PathCard
          side="data" n="01"
          title="Data & Analytics"
          sub="12+ years · 150+ clients · 500+ dashboards"
          line="Strategic consulting, turning raw data into decisive action."
          onHover={setHover} onEnter={onEnter}
        />
        <PathCard
          side="mind" n="02"
          title="Mindfulness Training"
          sub="8+ years · 500+ students · 2,000+ sessions"
          line="Guided practice for calm, focus, and lasting resilience."
          onHover={setHover} onEnter={onEnter}
        />
      </div>
    </div>
  );
}

function PathCard({ side, n, title, sub, line, onHover, onEnter }) {
  const align = side === 'data' ? 'flex-start' : 'flex-end';
  return (
    <div
      data-magnetic
      data-cursor={side === 'data' ? 'enter · data' : 'enter · mind'}
      onMouseEnter={() => onHover(side)}
      onMouseLeave={() => onHover(null)}
      onClick={() => onEnter(side)}
      style={{
        cursor: 'pointer', padding: '24px 0',
        display: 'flex', flexDirection: 'column',
        alignItems: align, gap: 14,
        borderTop: '1px solid var(--rule-faint)',
        transition: 'opacity 400ms, transform 400ms cubic-bezier(.2,.7,.2,1)',
      }}>
      <div className="num" style={{ color: 'var(--ink-3)' }}>{n} <span className="dot"/> {side === 'data' ? 'cold light' : 'warm light'}</div>
      <div style={{
        fontFamily: 'var(--serif)', fontSize: 44, letterSpacing: '-0.02em',
        fontWeight: 400,
      }}>{title} <span style={{ fontStyle: 'italic', color: 'var(--ink-3)' }}>→</span></div>
      <div className="num">{sub}</div>
      <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 16, color: 'var(--ink-3)' }}>{line}</div>
    </div>
  );
}

// ─── Layout B · Split ──────────────────────────────────────────
function SplitLayout({ hover, setHover, onEnter }) {
  const sides = [
    { k: 'data', title: 'Data & Analytics', n: '01', w: 'cold light', stats: '12+ y · 150+ clients · 500+ dashboards', line: 'Strategic consulting that turns raw data into decisive action.' },
    { k: 'mind', title: 'Mindfulness Training', n: '02', w: 'warm light', stats: '8+ y · 500+ students · 2,000+ sessions', line: 'Guided programs that cultivate calm, focus, and resilience.' },
  ];
  return (
    <div style={{
      position: 'relative', zIndex: 2, height: '100%',
      display: 'grid', gridTemplateColumns: '1fr 1fr',
    }}>
      {sides.map((s, i) => (
        <div key={s.k}
          onMouseEnter={() => setHover(s.k)}
          onMouseLeave={() => setHover(null)}
          onClick={() => onEnter(s.k)}
          style={{
            padding: '160px 60px 60px',
            borderRight: i === 0 ? '1px solid var(--rule-faint)' : 'none',
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
            cursor: 'pointer',
            transition: 'background 400ms',
          }}>
          <div className="num" style={{ color: 'var(--ink-3)' }}>
            {s.n} <span className="dot"/> {s.w}
          </div>
          <div>
            <div style={{
              fontFamily: 'var(--serif)', fontSize: 'clamp(54px, 6vw, 104px)',
              lineHeight: 0.95, letterSpacing: '-0.03em', fontWeight: 400,
            }}>{s.title}</div>
            <div style={{
              fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 24,
              color: 'var(--ink-3)', marginTop: 24,
            }}>{s.line}</div>
            <div className="num" style={{ marginTop: 56 }}>
              {s.stats}
            </div>
            <div className="num" style={{ marginTop: 14, color: 'var(--ink)' }}>
              enter <span className="dot"/> →
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Layout C · Manifesto ──────────────────────────────────────
function ManifestoLayout({ hover, setHover, onEnter }) {
  return (
    <div style={{
      position: 'relative', zIndex: 2, height: '100%',
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      padding: '120px 60px 60px',
    }}>
      <div className="num" style={{ color: 'var(--ink-3)', marginBottom: 40 }}>
        A manifesto in three lines
      </div>
      {[
        ['Insight', 'is what data gives a leader who is willing to look honestly.'],
        ['Awareness', 'is what mindfulness gives a leader who is willing to be still.'],
        ['Both', 'are the practice of seeing clearly — applied to different surfaces.'],
      ].map(([a, b], i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: '40px 1fr 1fr',
          gap: 32, padding: '28px 0',
          borderTop: '1px solid var(--rule-faint)',
          alignItems: 'baseline',
        }}>
          <div className="num">{String(i + 1).padStart(2, '0')}</div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 'clamp(36px, 4vw, 64px)', letterSpacing: '-0.02em' }}>{a}</div>
          <div style={{ fontFamily: 'var(--serif)', fontStyle: 'italic', fontSize: 'clamp(24px, 2.6vw, 40px)', color: 'var(--ink-3)' }}>{b}</div>
        </div>
      ))}
      <div style={{ display: 'flex', gap: 24, marginTop: 80 }}>
        <button className="btn btn-solid" onClick={() => onEnter('data')}>Data & Analytics <span className="dot"/> →</button>
        <button className="btn" onClick={() => onEnter('mind')}>Mindfulness <span className="dot"/> →</button>
      </div>
    </div>
  );
}

window.Gateway = Gateway;
