/* global React */

const CHAPTER_DOTS = [
  { id: "frisco",   label: "Frisco, Texas",  sub: "Headquarters · Largest Chapter", lat: 33.15, lon: -96.82, big: true,  ox: -13, oy: 0 },
  { id: "prosper",  label: "Prosper, Texas", sub: "Chapter",                        lat: 33.24, lon: -96.80, big: false, ox:  13, oy: 0 },
  { id: "virginia", label: "Virginia",       sub: "Chapter",                        lat: 38.88, lon: -77.10, big: false, ox: 0,   oy: 0 },
  { id: "india",    label: "India",          sub: "Chapter",                        lat: 28.61, lon:  77.21, big: false, ox: 0,   oy: 0 },
  { id: "taiwan",   label: "Taiwan",         sub: "Chapter",                        lat: 25.03, lon: 121.56, big: false, ox: 0,   oy: 0 },
];

// equirectangular, clipped lat -60..80
const LAT0 = -60, LAT1 = 80, LON0 = -180, LON1 = 180;

function toPct(lat, lon) {
  return {
    x: (lon - LON0) / (LON1 - LON0) * 100,
    y: (LAT1 - lat)  / (LAT1 - LAT0) * 100,
  };
}

function isLand(lat, lon) {
  // Greenland
  if (lat >= 60 && lat <= 84 && lon >= -57 && lon <= -17) return true;
  // Iceland
  if (lat >= 63 && lat <= 67 && lon >= -25 && lon <= -12) return true;
  // Alaska
  if (lat >= 54 && lat <= 72 && lon >= -170 && lon <= -130) return true;
  // Canada + N US
  if (lat >= 48 && lat <= 72 && lon >= -140 && lon <= -52) return true;
  // Continental US
  if (lat >= 25 && lat < 48 && lon >= -124 && lon <= -66) return true;
  // Mexico + Central America
  if (lat >= 7 && lat < 25 && lon >= -118 && lon <= -77) return true;
  // Caribbean
  if (lat >= 17 && lat <= 24 && lon >= -85 && lon <= -68) return true;
  // NW South America
  if (lat >= 0 && lat <= 12 && lon >= -82 && lon <= -60) return true;
  // South America
  if (lat >= -5 && lat < 0  && lon >= -80 && lon <= -50) return true;
  if (lat >= -20 && lat < -5  && lon >= -80 && lon <= -34) return true;
  if (lat >= -35 && lat < -20 && lon >= -75 && lon <= -48) return true;
  if (lat >= -55 && lat < -35 && lon >= -76 && lon <= -55) return true;
  // UK + Ireland
  if (lat >= 50 && lat <= 59 && lon >= -11 && lon <= 2) return true;
  // Scandinavia + Finland
  if (lat >= 55 && lat <= 72 && lon >= 4 && lon <= 32) return true;
  // Continental Europe + Turkey
  if (lat >= 35 && lat < 55 && lon >= -10 && lon <= 42) return true;
  // European Russia
  if (lat >= 50 && lat <= 72 && lon >= 28 && lon <= 62) return true;
  // Siberia
  if (lat >= 50 && lat <= 76 && lon >= 60 && lon <= 180) return true;
  // Central Asia
  if (lat >= 36 && lat < 50 && lon >= 50 && lon <= 90) return true;
  // Middle East + Arabia
  if (lat >= 12 && lat <= 42 && lon >= 35 && lon <= 64) return true;
  // North Africa
  if (lat >= 15 && lat <= 38 && lon >= -18 && lon <= 52) return true;
  // West Africa
  if (lat >= 0 && lat < 15 && lon >= -18 && lon <= 18) return true;
  // Central + East Africa
  if (lat >= -12 && lat < 15 && lon >= 8 && lon <= 52) return true;
  // Southern Africa
  if (lat >= -35 && lat < -12 && lon >= 12 && lon <= 52) return true;
  // Madagascar
  if (lat >= -26 && lat <= -12 && lon >= 43 && lon <= 51) return true;
  // South Asia
  if (lat >= 6 && lat <= 37 && lon >= 60 && lon <= 97) return true;
  // China + Mongolia
  if (lat >= 18 && lat <= 55 && lon >= 73 && lon <= 135) return true;
  // Korea + Japan + Taiwan
  if (lat >= 24 && lat <= 46 && lon >= 120 && lon <= 146) return true;
  // SE Asia mainland
  if (lat >= 0 && lat < 25 && lon >= 92 && lon <= 115) return true;
  // Philippines
  if (lat >= 4 && lat <= 21 && lon >= 116 && lon <= 127) return true;
  // Indonesia (simplified)
  if (lat >= -10 && lat <= 6 && lon >= 95 && lon <= 125) return true;
  if (lat >= -9  && lat <= -5 && lon >= 110 && lon <= 141) return true;
  // Australia
  if (lat >= -43 && lat <= -11 && lon >= 114 && lon <= 154) return true;
  // New Zealand
  if (lat >= -47 && lat <= -34 && lon >= 166 && lon <= 178) return true;
  return false;
}

function ChaptersMap({ hoveredId, onHover }) {
  const canvasRef   = React.useRef(null);
  const wrapRef     = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const wrap   = wrapRef.current;
    if (!canvas || !wrap) return;

    const draw = () => {
      const W = wrap.offsetWidth;
      const H = wrap.offsetHeight;
      if (!W || !H) return;
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      canvas.width  = W * dpr;
      canvas.height = H * dpr;
      const ctx = canvas.getContext('2d');
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, W, H);

      for (let lat = LAT0; lat <= LAT1; lat += 2.5) {
        for (let lon = LON0; lon <= LON1; lon += 2.5) {
          if (!isLand(lat, lon)) continue;
          const px = (lon - LON0) / (LON1 - LON0) * W;
          const py = (LAT1 - lat) / (LAT1 - LAT0) * H;
          ctx.beginPath();
          ctx.arc(px, py, 1.3, 0, Math.PI * 2);
          ctx.fillStyle = 'rgba(255,255,255,0.26)';
          ctx.fill();
        }
      }
    };

    draw();
    const ro = new ResizeObserver(draw);
    ro.observe(wrap);
    return () => ro.disconnect();
  }, []);

  const handleMove = React.useCallback((e) => {
    const wrap = wrapRef.current;
    if (!wrap) return;
    const rect = wrap.getBoundingClientRect();
    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
    const clientY = e.touches ? e.touches[0].clientY : e.clientY;
    const mx = clientX - rect.left;
    const my = clientY - rect.top;
    const W = rect.width, H = rect.height;
    let found = null, best = 32;
    for (const ch of CHAPTER_DOTS) {
      const cx = (ch.lon - LON0) / (LON1 - LON0) * W + (ch.ox || 0);
      const cy = (LAT1 - ch.lat) / (LAT1 - LAT0) * H + (ch.oy || 0);
      const d  = Math.hypot(mx - cx, my - cy);
      if (d < best) { best = d; found = ch.id; }
    }
    onHover(found);
  }, [onHover]);

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: '100%', height: '100%' }}
      onMouseMove={handleMove} onMouseLeave={() => onHover(null)}
      onTouchMove={handleMove} onTouchEnd={() => onHover(null)}>
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block' }} />

      {CHAPTER_DOTS.map((ch, i) => {
        const { x, y } = toPct(ch.lat, ch.lon);
        const active   = hoveredId === ch.id;
        const nearTop  = y < 18;
        const nearLeft = x < 12;
        const nearRight= x > 88;
        const tooltipStyle = {
          position: 'absolute',
          [nearTop ? 'top' : 'bottom']: 'calc(100% + 11px)',
          ...(nearLeft
            ? { left: 0, transform: 'none' }
            : nearRight
            ? { right: 0, transform: 'none' }
            : { left: '50%', transform: 'translateX(-50%)' }),
          background: 'rgba(4,9,5,0.95)',
          border: '1px solid rgba(92,124,95,0.4)',
          backdropFilter: 'blur(14px)',
          borderRadius: 10,
          padding: '9px 14px',
          whiteSpace: 'nowrap',
          pointerEvents: 'none',
          zIndex: 20,
        };

        return (
          <div key={ch.id} style={{
            position: 'absolute',
            left: `${x}%`, top: `${y}%`,
            transform: `translate(calc(-50% + ${ch.ox || 0}px), calc(-50% + ${ch.oy || 0}px))`,
            zIndex: 5,
          }}>
            {/* pulse ring */}
            <div style={{
              position: 'absolute',
              width:  ch.big ? 30 : 22,
              height: ch.big ? 30 : 22,
              top:  ch.big ? -9 : -7,
              left: ch.big ? -9 : -7,
              borderRadius: '50%',
              background: ch.big ? 'rgba(197,210,190,0.18)' : 'rgba(92,124,95,0.2)',
              animation: 'chapterPulse 2.6s ease-out infinite',
              animationDelay: `${i * 0.42}s`,
              pointerEvents: 'none',
            }} />
            {/* dot */}
            <div style={{
              width:  ch.big ? 12 : 8,
              height: ch.big ? 12 : 8,
              borderRadius: '50%',
              background: ch.big ? '#C5D2BE' : '#5C7C5F',
              boxShadow: ch.big
                ? '0 0 0 2px rgba(197,210,190,0.35), 0 0 18px rgba(197,210,190,0.65)'
                : '0 0 0 1.5px rgba(92,124,95,0.45), 0 0 10px rgba(92,124,95,0.55)',
              transition: 'transform 180ms ease',
              transform: active ? 'scale(1.8)' : 'scale(1)',
              cursor: 'default',
            }} />
            {/* tooltip */}
            {active && (
              <div style={tooltipStyle}>
                <div style={{ color: '#fff', fontWeight: 500, fontSize: 13, letterSpacing: '-0.01em' }}>{ch.label}</div>
                {ch.big && (
                  <div style={{ color: 'rgba(197,210,190,0.65)', fontSize: 10, fontFamily: 'var(--f-mono)', letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 3 }}>
                    {ch.sub}
                  </div>
                )}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function Chapters({ go }) {
  const [hoveredId, setHoveredId] = React.useState(null);

  React.useEffect(() => {
    document.body.classList.add('chapters-page');
    return () => document.body.classList.remove('chapters-page');
  }, []);

  return (
    <div style={{ background: '#060D07', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>

      {/* ── Header ── */}
      <div style={{ padding: 'clamp(28px,4vw,52px) var(--gutter) clamp(16px,2vw,28px)', display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 20 }}>
        <div>
          <span style={{ fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.32)', display: 'block', marginBottom: 14 }}>
            Willow Chapters
          </span>
          <h1 style={{ color: '#fff', fontSize: 'clamp(30px,5vw,62px)', fontWeight: 500, letterSpacing: '-0.035em', lineHeight: 0.96, margin: 0 }}>
            {CHAPTER_DOTS.length} chapters.<br/>
            <span style={{ fontFamily: 'var(--f-serif)', fontStyle: 'italic', color: '#91B093' }}>Across 3 continents.</span>
          </h1>
        </div>
        <button
          className="btn btn-lg"
          style={{ background: '#5C7C5F', color: '#fff', borderRadius: 'var(--r-pill)', flexShrink: 0 }}
          onClick={() => go('ambassador')}
        >
          Open a Chapter →
        </button>
      </div>

      {/* ── World map ── */}
      <div style={{ flex: 1, minHeight: 'clamp(280px, 52vh, 540px)', padding: '0 var(--gutter)' }}>
        <ChaptersMap hoveredId={hoveredId} onHover={setHoveredId} />
      </div>

      {/* ── Chapter list ── */}
      <div style={{ padding: 'clamp(20px,3vw,36px) var(--gutter) clamp(32px,4vw,56px)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(100%,220px),1fr))', gap: 10 }}>
          {CHAPTER_DOTS.map(ch => (
            <div
              key={ch.id}
              onMouseEnter={() => setHoveredId(ch.id)}
              onMouseLeave={() => setHoveredId(null)}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '13px 16px',
                borderRadius: 14,
                background: hoveredId === ch.id ? 'rgba(92,124,95,0.14)' : 'rgba(255,255,255,0.04)',
                border: `1px solid ${hoveredId === ch.id ? 'rgba(92,124,95,0.35)' : 'rgba(255,255,255,0.07)'}`,
                transition: 'background 180ms, border-color 180ms',
                cursor: 'default',
              }}
            >
              <div style={{
                width:  ch.big ? 10 : 7,
                height: ch.big ? 10 : 7,
                borderRadius: '50%', flexShrink: 0,
                background: ch.big ? '#C5D2BE' : '#5C7C5F',
                boxShadow: ch.big ? '0 0 8px rgba(197,210,190,0.7)' : '0 0 6px rgba(92,124,95,0.55)',
              }} />
              <div>
                <div style={{ color: '#fff', fontWeight: 500, fontSize: 14 }}>{ch.label}</div>
                {ch.big && <div style={{ color: 'rgba(255,255,255,0.32)', fontSize: 10, fontFamily: 'var(--f-mono)', letterSpacing: '0.06em', marginTop: 2 }}>{ch.sub}</div>}
              </div>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

window.Chapters = Chapters;
