// Real-geography destination map — loads world atlas TopoJSON, projects to SVG
const DestinationMap = ({ navigate, destinations }) => {
  const [hover, setHover] = React.useState(null);
  const [worldPath, setWorldPath] = React.useState(null);
  const [projector, setProjector] = React.useState(null);

  // Real lat/lng for our destinations
  const cities = {
    tijuana:  { lat: 32.5149, lng: -117.0382, name: 'Tijuana, MX',   region: 'Baja California' },
    cancun:   { lat: 21.1619, lng: -86.8515,  name: 'Cancún, MX',    region: 'Quintana Roo' },
    sanjose:  { lat: 9.9281,  lng: -84.0907,  name: 'San José, CR',  region: 'Costa Rica' },
    budapest: { lat: 47.4979, lng: 19.0402,   name: 'Budapest, HU',  region: 'Hungary' },
    bangkok:  { lat: 13.7563, lng: 100.5018,  name: 'Bangkok, TH',   region: 'Thailand' },
  };
  const colors = { tijuana:'#C25E3A', cancun:'#2E6F8E', sanjose:'#5C7A4F', budapest:'#C44569', bangkok:'#D9A14E' };

  const W = 960, H = 480;

  React.useEffect(() => {
    let cancelled = false;
    // Wait for d3-geo + topojson libs to be loaded (CDN)
    const tryLoad = async () => {
      if (!window.d3 || !window.topojson) {
        setTimeout(tryLoad, 100);
        return;
      }
      try {
        const res = await fetch('https://cdn.jsdelivr.net/npm/world-atlas@2.0.2/countries-110m.json');
        const topo = await res.json();
        if (cancelled) return;
        const land = window.topojson.feature(topo, topo.objects.land);
        const countries = window.topojson.feature(topo, topo.objects.countries);
        // Natural Earth projection — fits whole world cleanly
        const proj = window.d3.geoNaturalEarth1().fitSize([W, H], { type: 'Sphere' });
        const path = window.d3.geoPath(proj);
        setWorldPath({
          land: path(land),
          countries: countries.features.map(f => ({ id: f.id, name: f.properties && f.properties.name, d: path(f) })),
          sphere: path({ type:'Sphere' }),
          graticule: path(window.d3.geoGraticule10()),
        });
        setProjector(() => proj);
      } catch (e) {
        console.error('map load failed', e);
      }
    };
    tryLoad();
    return () => { cancelled = true; };
  }, []);

  // Project city to pixel coords
  const projectCity = (c) => projector ? projector([c.lng, c.lat]) : null;

  // Origin for travel lines: center of contiguous US (~Kansas)
  const origin = projector ? projector([-98.5, 39.5]) : null;

  // Highlight regions per hovered city (simple bbox)
  const highlightForCity = (id) => {
    if (!projector) return null;
    const m = {
      tijuana:  [[-128, 40], [-100, 18]],
      cancun:   [[-92, 23], [-86, 16]],
      sanjose:  [[-86, 12], [-82, 8]],
      budapest: [[12, 52], [28, 43]],
      bangkok:  [[95, 22], [110, 5]],
    }[id];
    if (!m) return null;
    const a = projector(m[0]), b = projector(m[1]);
    return { x: Math.min(a[0],b[0]), y: Math.min(a[1],b[1]), w: Math.abs(b[0]-a[0]), h: Math.abs(b[1]-a[1]) };
  };

  const active = hover ? destinations.find(d => d.id === hover) : null;
  const hl = hover ? highlightForCity(hover) : null;

  return (
    <div style={{position:'relative',background:'linear-gradient(180deg, #F4F1EA 0%, #ECE3CB 100%)',borderRadius:20,overflow:'hidden',boxShadow:'var(--shadow-card)',border:'1px solid var(--silver-300)'}}>
      <div style={{position:'absolute',top:24,left:28,zIndex:2,display:'flex',alignItems:'center',gap:10,pointerEvents:'none'}}>
        <span className="num-eyebrow" style={{color:'var(--silver-600)'}}>The Atlas</span>
        <span style={{width:1,height:14,background:'var(--silver-400)'}}></span>
        <span style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--silver-500)',letterSpacing:'0.08em',textTransform:'uppercase'}}>5 destinations · 47 clinics · click any pin</span>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%',height:'auto',display:'block'}}>
        <defs>
          <linearGradient id="ocean-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#E8EEF1"/>
            <stop offset="1" stopColor="#CBD9DD"/>
          </linearGradient>
          <linearGradient id="land-grad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#F4EBD0"/>
            <stop offset="1" stopColor="#DEC998"/>
          </linearGradient>
          <filter id="land-shadow" x="-5%" y="-5%" width="110%" height="110%">
            <feDropShadow dx="0" dy="1.5" stdDeviation="2" floodOpacity="0.18"/>
          </filter>
        </defs>

        {/* Ocean fill (sphere) */}
        {worldPath ? <path d={worldPath.sphere} fill="url(#ocean-grad)" stroke="#A89978" strokeWidth="0.6"/> : <rect width={W} height={H} fill="url(#ocean-grad)"/>}

        {/* Graticule */}
        {worldPath && <path d={worldPath.graticule} fill="none" stroke="#0B0D0C" strokeWidth="0.4" opacity="0.08"/>}

        {/* Land masses */}
        {worldPath && (
          <g filter="url(#land-shadow)">
            <path d={worldPath.land} fill="url(#land-grad)" stroke="#A89978" strokeWidth="0.5"/>
          </g>
        )}

        {/* Country outlines (subtle) */}
        {worldPath && (
          <g fill="none" stroke="#A89978" strokeWidth="0.4" opacity="0.55">
            {worldPath.countries.slice(0, 250).map((c, i) => <path key={i} d={c.d}/>)}
          </g>
        )}

        {/* Highlight rectangle for hovered region */}
        {hl && (
          <rect x={hl.x-8} y={hl.y-8} width={hl.w+16} height={hl.h+16} fill={colors[hover]} opacity="0.10" stroke={colors[hover]} strokeWidth="1" strokeDasharray="3 3" rx="4"/>
        )}

        {/* Travel lines from US origin to each destination, as great-circle arcs */}
        {projector && origin && Object.entries(cities).map(([k, c]) => {
          const p = projectCity(c);
          if (!p) return null;
          const mx = (origin[0] + p[0]) / 2;
          const my = (origin[1] + p[1]) / 2 - Math.abs(p[0]-origin[0]) * 0.18 - 30;
          return (
            <path key={k} d={`M${origin[0]} ${origin[1]} Q ${mx} ${my} ${p[0]} ${p[1]}`} fill="none" stroke={colors[k]} strokeWidth={hover===k ? 1.6 : 1} strokeDasharray="2 4" opacity={hover && hover !== k ? 0.18 : 0.55}/>
          );
        })}

        {/* US origin marker */}
        {origin && (
          <g>
            <circle cx={origin[0]} cy={origin[1]} r="3" fill="#0B0D0C"/>
            <circle cx={origin[0]} cy={origin[1]} r="7" fill="none" stroke="#0B0D0C" strokeWidth="0.6" opacity="0.4"/>
            <text x={origin[0]} y={origin[1]+18} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" letterSpacing="0.1em" fill="#5E6470">YOU ARE HERE</text>
          </g>
        )}

        {/* Pins */}
        {projector && Object.entries(cities).map(([k, c]) => {
          const p = projectCity(c);
          if (!p) return null;
          const isHover = hover === k;
          const col = colors[k];
          return (
            <g key={k} onClick={() => navigate('destination', k)} onMouseEnter={() => setHover(k)} onMouseLeave={() => setHover(null)} style={{cursor:'pointer'}}>
              {/* pulse */}
              <circle cx={p[0]} cy={p[1]} r="22" fill={col} opacity="0.10">
                <animate attributeName="r" values="14;26;14" dur="3s" repeatCount="indefinite"/>
                <animate attributeName="opacity" values="0.18;0.04;0.18" dur="3s" repeatCount="indefinite"/>
              </circle>
              {/* halo */}
              <circle cx={p[0]} cy={p[1]} r={isHover ? 13 : 10} fill="white" stroke={col} strokeWidth="2"/>
              {/* dot */}
              <circle cx={p[0]} cy={p[1]} r={isHover ? 6 : 4.5} fill={col}/>
              {/* label */}
              <g transform={`translate(${p[0] + 12}, ${p[1] - 4})`} style={{pointerEvents:'none'}}>
                <rect x="0" y="-11" width={c.name.length * 6.4 + 12} height="18" rx="9" fill="white" stroke={col} strokeWidth="0.8"/>
                <text x="6" y="2.5" fontFamily="var(--font-serif)" fontSize="11" fill="#0B0D0C" letterSpacing="-0.005em">{c.name}</text>
              </g>
            </g>
          );
        })}

        {/* Compass rose */}
        <g transform={`translate(${W-50}, 60)`} opacity="0.7">
          <circle r="22" fill="white" stroke="#A89978" strokeWidth="0.8"/>
          <path d="M0 -18 L4.5 0 L0 18 L-4.5 0 Z" fill="#0B0D0C"/>
          <path d="M-18 0 L0 -3.5 L18 0 L0 3.5 Z" fill="#A89978" opacity="0.6"/>
          <text y="-25" textAnchor="middle" fontFamily="var(--font-mono)" fontSize="8" fill="#5E6470">N</text>
        </g>

        {/* Loading state */}
        {!worldPath && (
          <text x={W/2} y={H/2} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="11" fill="#5E6470" letterSpacing="0.15em">⟳ LOADING ATLAS…</text>
        )}
      </svg>

      {/* Destination preview card on hover */}
      {active && (
        <div style={{position:'absolute',right:24,top:80,width:280,padding:'18px 20px',background:'rgba(255,255,255,0.96)',backdropFilter:'blur(8px)',border:'1px solid var(--silver-300)',borderRadius:14,boxShadow:'var(--shadow-pop)',pointerEvents:'none'}}>
          <div className="num-eyebrow" style={{marginBottom:6,color: colors[active.id]}}>{active.region}</div>
          <div style={{fontFamily:'var(--font-serif)',fontSize:24,letterSpacing:'-0.015em',marginBottom:6}}>{active.name}</div>
          <p style={{fontSize:13,color:'var(--fg-2)',lineHeight:1.5,margin:'0 0 12px',fontStyle:'italic'}}>{active.tagline}</p>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,fontSize:13}}>
            <div><div className="num-eyebrow">Save</div><div style={{fontFamily:'var(--font-serif)',fontSize:18,color:'var(--moss)'}}>{active.avgSavings}%</div></div>
            <div><div className="num-eyebrow">Travel</div><div style={{fontFamily:'var(--font-serif)',fontSize:14}}>{active.flightHrs}</div></div>
          </div>
          <div style={{marginTop:12,paddingTop:10,borderTop:'1px solid var(--silver-200)',fontFamily:'var(--font-mono)',fontSize:11,color:'var(--terracotta)'}}>Click to explore →</div>
        </div>
      )}

      {/* Legend */}
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'14px 28px 18px',background:'linear-gradient(180deg, transparent 0%, rgba(255,255,255,0.6) 100%)'}}>
        <div style={{display:'flex',gap:18,fontFamily:'var(--font-mono)',fontSize:10,letterSpacing:'0.08em',textTransform:'uppercase',color:'var(--silver-600)',flexWrap:'wrap'}}>
          {Object.entries(colors).map(([k,c]) => (
            <button key={k} onClick={() => navigate('destination', k)} onMouseEnter={() => setHover(k)} onMouseLeave={() => setHover(null)} style={{display:'inline-flex',alignItems:'center',gap:7,border:'none',background:'transparent',cursor:'pointer',fontFamily:'inherit',fontSize:'inherit',letterSpacing:'inherit',textTransform:'inherit',color: hover===k ? 'var(--ink)' : 'inherit',transition:'color 160ms'}}>
              <span style={{width:8,height:8,borderRadius:999,background:c,boxShadow:`0 0 8px ${c}`}}></span>{cities[k].name.split(',')[0]}
            </button>
          ))}
        </div>
        <span style={{fontFamily:'var(--font-mono)',fontSize:10,color:'var(--silver-500)',letterSpacing:'0.08em',textTransform:'uppercase'}}>↘ Coming · Cartagena · Istanbul · Phuket</span>
      </div>
    </div>
  );
};

window.DestinationMap = DestinationMap;
