// page-download.jsx — Download / Get App page
// Unique overlay: phone mockup that tilts in 3D following the cursor,
// plus QR code panels.

function DownloadPage() {
  return (
    <window.PageShell
      active="Download"
      eyebrow="005 / DOWNLOAD"
      title="On your phone, in your pocket. Always running."
      subtitle="iPhone-first, with Android in development. The probe runs server-side; the app is a thin window into your watches and a fast deeplink to Recreation.gov."
    >
      <DownloadHero/>
      <FeatureBullets/>
      <SystemReqs/>
    </window.PageShell>
  );
}

function DownloadHero() {
  const T = window.useTokens();
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });
  const ref = React.useRef(null);

  const onMove = (e) => {
    const rect = ref.current?.getBoundingClientRect();
    if (!rect) return;
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const dx = (e.clientX - cx) / rect.width;
    const dy = (e.clientY - cy) / rect.height;
    setTilt({ x: dy * 14, y: -dx * 14 });
  };
  const onLeave = () => setTilt({ x: 0, y: 0 });

  return (
    <section ref={ref} onMouseMove={onMove} onMouseLeave={onLeave}
      style={{
        position: 'relative', padding: '80px 40px',
        background: T.bg2, borderBottom: `1px solid ${T.border}`,
        overflow: 'hidden',
      }}>
      <DownloadGridBg/>
      <div style={{
        maxWidth: 1100, margin: '0 auto', position: 'relative', zIndex: 2,
        display: 'grid', gridTemplateColumns: '1fr 380px', gap: 80, alignItems: 'center',
      }}>
        {/* Left: download CTAs hidden pre-launch */}
        <div>
          <div style={{
            fontFamily: T.mono, fontSize: 11, letterSpacing: 2,
            color: T.amber, marginBottom: 20,
          }}>─── COMING SOON ───</div>

          <p style={{
            fontFamily: T.mono, fontSize: 12, color: T.textMute,
            lineHeight: 1.6, margin: 0, maxWidth: 400,
          }}>
            The app is not yet available for public download.
          </p>
        </div>

        {/* Right: tilted phone */}
        <div style={{
          perspective: '1200px', display: 'flex', justifyContent: 'center',
        }}>
          <div style={{
            width: 280, height: 580,
            transform: `rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`,
            transition: 'transform 0.15s ease-out',
            transformStyle: 'preserve-3d',
          }}>
            <PhoneMockup T={T}/>
          </div>
        </div>
      </div>
    </section>
  );
}

function DownloadGridBg() {
  const T = window.useTokens();
  return (
    <svg width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
      style={{ position: 'absolute', inset: 0, opacity: 0.4, pointerEvents: 'none' }}>
      <defs>
        <pattern id="dl-grid" width="60" height="60" patternUnits="userSpaceOnUse">
          <path d="M 60 0 L 0 0 0 60" fill="none" stroke={T.text} strokeWidth="0.4" opacity="0.18"/>
        </pattern>
        <radialGradient id="dl-fade" cx="50%" cy="50%" r="60%">
          <stop offset="0%" stopColor="white" stopOpacity="1"/>
          <stop offset="100%" stopColor="white" stopOpacity="0"/>
        </radialGradient>
        <mask id="dl-mask"><rect width="100%" height="100%" fill="url(#dl-fade)"/></mask>
      </defs>
      <rect width="100%" height="100%" fill="url(#dl-grid)" mask="url(#dl-mask)"/>
    </svg>
  );
}

function QRPanel({ T, platform, tag }) {
  return (
    <div style={{
      border: `1px solid ${T.border}`, background: T.bg3,
      padding: 14, display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <span style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6,
          color: T.textMute, fontWeight: 600 }}>{platform.toUpperCase()}</span>
        <span style={{ fontFamily: T.mono, fontSize: 9, color: T.textDim }}>{tag}</span>
      </div>
      <FakeQR T={T}/>
      <div style={{
        fontFamily: T.mono, fontSize: 9.5, letterSpacing: 1, color: T.textDim,
      }}>
        SHA-256: 4f2a9e..bd13
      </div>
    </div>
  );
}

function FakeQR({ T }) {
  // Deterministic pseudo-QR pattern
  const cells = [];
  for (let r = 0; r < 21; r++) {
    for (let c = 0; c < 21; c++) {
      const isCorner = (r < 7 && c < 7) || (r < 7 && c > 13) || (r > 13 && c < 7);
      const seed = (r * 7 + c * 13 + r * c) % 5;
      const filled = isCorner ? cornerCell(r, c) : seed === 0 || seed === 2;
      if (filled) cells.push(<rect key={`${r}-${c}`} x={c * 6} y={r * 6} width="6" height="6" fill={T.text}/>);
    }
  }
  return (
    <svg viewBox="0 0 126 126" width="100%" style={{ background: T.bg2,
      border: `1px solid ${T.border}` }}>
      {cells}
    </svg>
  );
}

function cornerCell(r, c) {
  const lr = r >= 14 ? r - 14 : r;
  const lc = c >= 14 ? c - 14 : c;
  if (lr === 0 || lr === 6 || lc === 0 || lc === 6) return true;
  if (lr >= 2 && lr <= 4 && lc >= 2 && lc <= 4) return true;
  return false;
}

function StoreButton({ T, store }) {
  return (
    <a href="#" style={{
      flex: 1, display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 16px', border: `1px solid ${T.border}`,
      background: T.bg3, color: T.text, textDecoration: 'none',
      transition: 'all 0.2s',
    }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = T.amber; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = T.border; }}>
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        {store === 'App Store' ? (
          <path d="M18 13.5c0-2.6 2.1-3.8 2.2-3.9-1.2-1.8-3.1-2-3.7-2-1.6-.2-3.1.9-3.9.9-.8 0-2-.9-3.4-.9-1.7 0-3.4 1-4.3 2.6-1.8 3.2-.5 7.9 1.3 10.5.9 1.3 1.9 2.7 3.3 2.6 1.3-.1 1.8-.8 3.4-.8 1.6 0 2 .8 3.4.8 1.4 0 2.3-1.3 3.2-2.6 1-1.5 1.4-2.9 1.5-3-.1 0-2.9-1.1-3-4.2zM15.5 5.5c.7-.9 1.2-2.1 1-3.3-1 .1-2.3.7-3 1.5-.7.8-1.2 2-1 3.2 1.1.1 2.3-.5 3-1.4z"/>
        ) : (
          <path d="M3 4.5v15l8-7.5L3 4.5zm9.5 7.5L21 19V5l-8.5 7zm-1 .5l-7 6.5h14l-7-6.5z"/>
        )}
      </svg>
      <div>
        <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.2,
          color: T.textDim }}>DOWNLOAD ON</div>
        <div style={{ fontFamily: T.mono, fontSize: 12, fontWeight: 600,
          letterSpacing: 0.5 }}>{store.toUpperCase()}</div>
      </div>
    </a>
  );
}

function PhoneMockup({ T }) {
  return (
    <div style={{
      width: '100%', height: '100%',
      borderRadius: 36, background: '#000',
      padding: 8, position: 'relative',
      boxShadow: `0 30px 80px ${T.amberFog}, 0 0 0 1px ${T.borderStrong}`,
    }}>
      <div style={{
        width: '100%', height: '100%', borderRadius: 28,
        background: T.bg, overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Status bar */}
        <div style={{
          padding: '14px 20px', display: 'flex',
          justifyContent: 'space-between', alignItems: 'center',
          fontFamily: T.mono, fontSize: 10, color: T.text, letterSpacing: 1,
        }}>
          <span>9:41</span>
          <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
            <span style={{ fontSize: 8 }}>● ● ●</span>
          </div>
        </div>
        {/* App content */}
        <div style={{ flex: 1, padding: '12px 16px',
          display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            paddingBottom: 8, borderBottom: `1px solid ${T.border}`,
          }}>
            <span style={{ fontFamily: T.mono, fontSize: 11, fontWeight: 600,
              color: T.text, letterSpacing: 1.2 }}>WATCHES</span>
            <span style={{ fontFamily: T.mono, fontSize: 10, color: T.amber }}>+ NEW</span>
          </div>
          {[
            ['Yosemite · Upper Pines', 'ARMED', T.amber],
            ['Zion · Watchman', 'ARMED', T.amber],
            ['Glacier · Apgar', 'PAUSED', T.textDim],
            ['Rocky Mtn · Moraine', 'ARMED', T.amber],
          ].map(([name, status, c], i) => (
            <div key={i} style={{
              padding: '10px 12px', border: `1px solid ${T.border}`,
              background: T.bg3,
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <span style={{ fontFamily: T.mono, fontSize: 10, color: T.text }}>{name}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 5, height: 5, borderRadius: '50%', background: c,
                  boxShadow: status === 'ARMED' ? `0 0 6px ${c}` : 'none' }}/>
                <span style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: 1.2,
                  color: c }}>{status}</span>
              </span>
            </div>
          ))}
          <div style={{ marginTop: 'auto', padding: '12px 14px',
            background: T.amberFog, border: `1px solid ${T.amber}` }}>
            <div style={{ fontFamily: T.mono, fontSize: 8.5, color: T.amber,
              letterSpacing: 1.4, marginBottom: 4 }}>● LATEST FIRE</div>
            <div style={{ fontFamily: T.mono, fontSize: 10, color: T.text }}>
              Yosemite #047 · 11s ago
            </div>
          </div>
        </div>
        {/* Tab bar */}
        <div style={{
          padding: '14px 20px', borderTop: `1px solid ${T.border}`,
          display: 'flex', justifyContent: 'space-around',
          fontFamily: T.mono, fontSize: 8, color: T.textDim, letterSpacing: 1.2,
        }}>
          <span>MAP</span><span style={{ color: T.amber }}>WATCHES</span>
          <span>ALERTS</span><span>YOU</span>
        </div>
      </div>
    </div>
  );
}

function FeatureBullets() {
  const T = window.useTokens();
  const items = [
    ['INSTANT PUSH', 'Notifications wake your phone before the email even arrives.'],
    ['1-TAP DEEPLINK', 'Tap the alert. The site pre-fills in Recreation.gov. Hit reserve.'],
    ['OFFLINE WATCH STATE', 'See and edit your watches without signal. Syncs when you reconnect.'],
    ['LOW POWER PROBE', 'All probing happens on our servers. Your battery never moves.'],
  ];
  return (
    <window.PageSection>
      <div style={{ fontFamily: T.mono, fontSize: 11, letterSpacing: 2,
        color: T.amber, marginBottom: 16 }}>─── ON-DEVICE ───</div>
      <h2 style={{
        fontFamily: T.mono, fontSize: 'clamp(28px, 3.5vw, 44px)', fontWeight: 600,
        letterSpacing: '-0.01em', margin: '0 0 40px',
        textTransform: 'uppercase', color: T.text,
      }}>The phone is just the trigger.</h2>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 1,
        background: T.border, border: `1px solid ${T.border}`,
      }}>
        {items.map(([label, body], i) => (
          <div key={i} style={{
            background: T.bg3, padding: '28px 24px',
          }}>
            <div style={{ fontFamily: T.mono, fontSize: 11, letterSpacing: 1.5,
              color: T.amber, marginBottom: 12, fontWeight: 600 }}>{label}</div>
            <p style={{ fontFamily: T.mono, fontSize: 12.5, lineHeight: 1.6,
              color: T.textMute, margin: 0 }}>{body}</p>
          </div>
        ))}
      </div>
    </window.PageSection>
  );
}

function SystemReqs() {
  const T = window.useTokens();
  return (
    <window.PageSection narrow dense>
      <div style={{
        border: `1px solid ${T.border}`, background: T.bg3,
        padding: '32px 28px', fontFamily: T.mono,
      }}>
        <div style={{ fontSize: 10, letterSpacing: 1.6, color: T.textDim,
          marginBottom: 16 }}>SYSTEM REQUIREMENTS</div>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24,
          fontSize: 12.5,
        }}>
          <div>
            <div style={{ color: T.amber, marginBottom: 8, letterSpacing: 1 }}>iOS</div>
            <div style={{ color: T.text, lineHeight: 1.8 }}>
              iOS 14.0+<br/>iPhone 7 or newer<br/>22MB install<br/>~3MB/mo data
            </div>
          </div>
          <div>
            <div style={{ color: T.amber, marginBottom: 8, letterSpacing: 1 }}>ANDROID</div>
            <div style={{ color: T.textMute, lineHeight: 1.8 }}>
              In development.<br/>Sign up below to<br/>be notified at launch.
            </div>
          </div>
        </div>
      </div>
    </window.PageSection>
  );
}

window.DownloadPage = DownloadPage;
