// Viewpoint — campus plan card (with meramec-authored pin positions + direction
// wedges) on the left, drag-to-compare before/after on the right.
function Radar() {
  const pins = [
    { id: 'north', x: 4,  y: 28, heading: 100, name: 'North Neighborhood', from: 'View from Prairie Ridge Dr.', dist: '0.8 mi',
      before: '/images/pin-1-before.webp', after: '/images/pin-1-after.webp' },
    { id: 'south', x: 27, y: 61, heading: 30,  name: 'South Open Space',   from: 'View from state park trail',  dist: '1.4 mi',
      before: '/images/pin-2-before.webp', after: '/images/pin-2-after.webp' },
    { id: 'east',  x: 78, y: 8,  heading: 245, name: 'East Homes',         from: 'View along County Rd 2850',   dist: '1.1 mi',
      before: '/images/pin-3-before.webp', after: '/images/pin-3-after.webp' },
  ];
  const [active, setActive] = useState(pins[0].id);
  const activePin = pins.find(p => p.id === active);
  const [split, setSplit] = useState(55);
  const dragging = useRef(false);
  const onMove = useCallback((clientX, rect) => {
    const pct = Math.max(2, Math.min(98, ((clientX - rect.left) / rect.width) * 100));
    setSplit(pct);
  }, []);
  const baRef = useRef(null);
  useEffect(() => {
    const up = () => { dragging.current = false; document.body.style.cursor = ''; };
    const move = (e) => {
      if (!dragging.current || !baRef.current) return;
      const rect = baRef.current.getBoundingClientRect();
      const cx = e.touches ? e.touches[0].clientX : e.clientX;
      onMove(cx, rect);
    };
    window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, { passive: true }); window.addEventListener('touchend', up);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); window.removeEventListener('touchmove', move); window.removeEventListener('touchend', up); };
  }, [onMove]);

  // SVG arc path for the direction wedge (cone). Compass: 0° = N (up), CW.
  const wedgePath = (headingDeg, fovDeg, radius) => {
    const start = ((headingDeg - fovDeg / 2 - 90) * Math.PI) / 180;
    const end   = ((headingDeg + fovDeg / 2 - 90) * Math.PI) / 180;
    const x1 = (radius * Math.cos(start)).toFixed(2);
    const y1 = (radius * Math.sin(start)).toFixed(2);
    const x2 = (radius * Math.cos(end)).toFixed(2);
    const y2 = (radius * Math.sin(end)).toFixed(2);
    const largeArc = fovDeg > 180 ? 1 : 0;
    return `M 0 0 L ${x1} ${y1} A ${radius} ${radius} 0 ${largeArc} 1 ${x2} ${y2} Z`;
  };

  return (
    <section id="viewpoint" style={{ padding: '140px 0 120px', background: 'var(--cream-50)', borderTop: '1px solid rgba(20,32,27,.1)' }}>
      <div className="container-x">
        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 80, alignItems: 'end', marginBottom: 56 }}>
          <div>
            <Reveal><div className="eyebrow"><span className="dot" /> Visual impact</div></Reveal>
            <Reveal delay={1}>
              <h2 className="h2" style={{ marginTop: 20 }}>
                Designed to recede <span className="italic-serif" style={{ color: 'var(--forest-800)' }}>into the landscape.</span>
              </h2>
            </Reveal>
          </div>
          <Reveal delay={2}>
            <p style={{ color: 'var(--slate-700)', fontSize: 16, lineHeight: 1.7, maxWidth: 520 }}>
              The most intensive activity stays in the campus interior. Earth berms, preserved tree lines, and 150‑foot perimeter setbacks keep the view from surrounding homes substantially the same as it is today. Select a viewpoint and drag to compare.
            </p>
          </Reveal>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '0.85fr 1.15fr', gap: 24, alignItems: 'stretch' }}>
          {/* Campus plan */}
          <Reveal>
            <div style={{ background: 'var(--white)', border: '1px solid rgba(20,32,27,.12)', padding: 24 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 16 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--slate-500)' }}>Fig. 02 · Campus plan</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--forest-800)' }}>{pins.length} viewpoints</div>
              </div>
              <div style={{ position: 'relative', aspectRatio: '27 / 20', background: 'var(--cream-50)', overflow: 'hidden' }}>
                <img src="/images/site-plan.webp" alt="Overhead site plan with viewpoint markers" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
                {/* Scale + compass overlay */}
                <div style={{ position: 'absolute', left: 12, bottom: 10, fontFamily: 'var(--font-body)', fontSize: 10, letterSpacing: '.18em', textTransform: 'uppercase', color: 'rgba(20,32,27,.55)' }}>N ↑   SCALE 1:3000</div>

                {/* Pins — meramec-style: numbered green circle + direction wedge cone + needle */}
                {pins.map((p, i) => {
                  const isActive = p.id === active;
                  const headingRad = (p.heading * Math.PI) / 180;
                  const needleX = (52.8 * Math.sin(headingRad)).toFixed(2);
                  const needleY = (-52.8 * Math.cos(headingRad)).toFixed(2);
                  return (
                    <button key={p.id} onClick={() => setActive(p.id)}
                      aria-label={`Viewpoint ${i + 1}: ${p.name}`}
                      style={{
                        position: 'absolute',
                        left: `${p.x}%`, top: `${p.y}%`,
                        transform: `translate(-50%,-50%) scale(${isActive ? 1.14 : 1})`,
                        transition: 'transform .18s cubic-bezier(.4,0,.2,1), background .18s, box-shadow .18s',
                        width: 28, height: 28, borderRadius: '50%',
                        background: isActive ? '#166534' : 'rgba(45,90,61,.88)',
                        boxShadow: isActive
                          ? '0 1px 0 rgba(0,0,0,.35), 0 6px 16px rgba(0,0,0,.32)'
                          : '0 1px 0 rgba(0,0,0,.35), 0 4px 12px rgba(0,0,0,.25)',
                        border: isActive ? '2px solid rgba(255,255,255,.9)' : '2px solid rgba(255,255,255,.7)',
                        color: '#f8f6f0',
                        fontFamily: 'Inter, sans-serif',
                        fontSize: 13, fontWeight: 600, lineHeight: 1,
                        padding: 0, cursor: 'pointer',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        touchAction: 'manipulation',
                      }}>
                      {/* Direction wedge (cone + needle) */}
                      <svg aria-hidden="true" viewBox="-110 -110 220 220"
                        style={{
                          position: 'absolute', left: '50%', top: '50%',
                          width: 220, height: 220,
                          transform: 'translate(-50%,-50%)',
                          overflow: 'visible',
                          mixBlendMode: 'overlay',
                          pointerEvents: 'none',
                        }}>
                        <defs>
                          <radialGradient id={`wedge-cone-${p.id}`} cx="0" cy="0" r="88" gradientUnits="userSpaceOnUse">
                            <stop offset="0%"   stopColor="#ffffff" stopOpacity={isActive ? 0.85 : 0.32} />
                            <stop offset="60%"  stopColor="#ffffff" stopOpacity={isActive ? 0.22 : 0.08} />
                            <stop offset="100%" stopColor="#ffffff" stopOpacity="0" />
                          </radialGradient>
                        </defs>
                        <path d={wedgePath(p.heading, isActive ? 72 : 60, 88)} fill={`url(#wedge-cone-${p.id})`} />
                        <line x1="0" y1="0" x2={needleX} y2={needleY}
                          stroke="rgba(8,14,11,.7)" strokeWidth="1.5" strokeLinecap="round"
                          strokeOpacity={isActive ? 0.95 : 0.55} />
                      </svg>
                      <span style={{ position: 'relative', zIndex: 10, transform: 'translateY(-.5px)' }}>{i + 1}</span>
                    </button>
                  );
                })}
              </div>
              <div style={{ marginTop: 16, borderTop: '1px solid rgba(20,32,27,.14)' }}>
                {pins.map((p, i) => {
                  const isActive = p.id === active;
                  return (
                    <button key={p.id} onClick={() => setActive(p.id)}
                      style={{ width: '100%', textAlign: 'left', padding: '16px 0', background: 'transparent', border: 'none', borderBottom: '1px solid rgba(20,32,27,.08)', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12, color: isActive ? 'var(--ink)' : 'var(--slate-700)' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <span aria-hidden="true" style={{
                          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                          width: 22, height: 22, borderRadius: '50%',
                          background: isActive ? '#166534' : 'rgba(45,90,61,.88)',
                          color: '#f8f6f0',
                          fontSize: 11, fontWeight: 600, fontFamily: 'Inter, sans-serif', lineHeight: 1,
                          border: '2px solid rgba(255,255,255,.7)',
                        }}>{i + 1}</span>
                        <div>
                          <div className="font-display" style={{ fontWeight: 500, fontSize: 16, color: 'var(--ink)' }}>{p.name}</div>
                          <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--slate-500)', marginTop: 4 }}>{p.from}</div>
                        </div>
                      </div>
                      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--accent-deep)' }}>{p.dist}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          </Reveal>

          {/* Before/After */}
          <Reveal delay={1}>
            <div style={{ background: 'var(--white)', border: '1px solid rgba(20,32,27,.12)', padding: 24, display: 'flex', flexDirection: 'column' }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 16 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--slate-500)' }}>
                  {activePin.name} · {activePin.from}
                </div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.22em', textTransform: 'uppercase', color: 'var(--accent-deep)' }}>Drag to compare</div>
              </div>
              <div ref={baRef} className="ba-wrap" style={{ aspectRatio: '16 / 10', cursor: 'ew-resize', '--split': `${split}%` }}
                   onMouseDown={(e) => { dragging.current = true; document.body.style.cursor = 'ew-resize'; onMove(e.clientX, e.currentTarget.getBoundingClientRect()); }}
                   onTouchStart={(e) => { dragging.current = true; onMove(e.touches[0].clientX, e.currentTarget.getBoundingClientRect()); }}>
                <div style={{ position:'absolute', inset: 0, background: `url(${activePin.before}) center/cover` }}>
                  <div style={{ position: 'absolute', top: 16, left: 16, padding: '6px 12px', background: 'rgba(20,32,27,.7)', color: 'var(--cream-50)', fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.2em', textTransform: 'uppercase' }}>Current</div>
                </div>
                <div className="ba-after" style={{ background: `url(${activePin.after}) center/cover` }}>
                  <div style={{ position: 'absolute', top: 16, right: 16, padding: '6px 12px', background: 'var(--forest-900)', color: 'var(--cream-50)', fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '.2em', textTransform: 'uppercase' }}>With campus</div>
                </div>
                <div className="ba-handle" style={{ background: 'var(--cream-50)', boxShadow: '0 0 0 1px rgba(20,32,27,.3)' }} />
                <div className="ba-knob" style={{ background: 'var(--cream-50)', borderRadius: 0 }} aria-hidden>
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M6 3 L2 8 L6 13 M10 3 L14 8 L10 13" stroke="var(--ink)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, marginTop: 24, borderTop: '1px solid rgba(20,32,27,.14)', borderBottom: '1px solid rgba(20,32,27,.14)' }}>
                {[
                  { k: '150 ft', v: 'Minimum setback' },
                  { k: '10%+', v: 'Open space preserved' },
                  { k: 'Interior', v: 'Equipment orientation' },
                ].map((s,i) => (
                  <div key={i} style={{ padding: '18px 18px 18px 0', borderRight: i < 2 ? '1px solid rgba(20,32,27,.1)' : 'none', paddingLeft: i > 0 ? 18 : 0 }}>
                    <div className="font-display num" style={{ fontWeight: 500, fontSize: 26, letterSpacing: '-0.01em', color: 'var(--ink)' }}>{s.k}</div>
                    <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--slate-500)', marginTop: 4 }}>{s.v}</div>
                  </div>
                ))}
              </div>
              <div style={{ fontFamily: 'var(--font-italic)', fontStyle: 'italic', fontSize: 14, color: 'var(--slate-500)', marginTop: 16, lineHeight: 1.55 }}>
                Photographs are reference imagery. Final renderings will be produced once the site design is finalized.
              </div>
            </div>
          </Reveal>
        </div>
      </div>
      <style>{`@media(max-width: 960px){ #viewpoint > .container-x > div { grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}
window.Radar = Radar;
