// GLOBAL REACH
// A minimal world map — continent silhouettes rendered as a stippled dot
// matrix (no kitsch). Origin nodes = where we source. Destination arcs =
// where product moves. Designed to feel like a navigator's chart, not an
// infographic. Map projected with manual lon/lat → SVG mapping (equirectangular).
function Reach() {
  const [active, setActive] = React.useState('all');

  // Equirectangular projection: lon (-180..180) → x (0..1000), lat (90..-90) → y (0..500)
  const proj = (lon, lat) => [
    ((lon + 180) / 360) * 1000,
    ((90 - lat) / 180) * 500,
  ];

  // Origins: Latin America. Each lists its primary destination markets.
  const origins = [
    { id:'mx', name:'Mexico',      lon:-102.5,lat:23.6,  type:'octopus',                     ships:['us','es'] },
    { id:'gt', name:'Guatemala',   lon:-90.5, lat:15.5,  type:'shrimp',                      ships:['us'] },
    { id:'ho', name:'Honduras',    lon:-86.5, lat:14.6,  type:'shrimp · lobster',            ships:['us','eu'] },
    { id:'ni', name:'Nicaragua',   lon:-85.2, lat:12.9,  type:'lobster',                     ships:['us'] },
    { id:'ec', name:'Ecuador',     lon:-78.4, lat:-1.5,  type:'shrimp · fish',               ships:['us','eu','jp'] },
    { id:'cl', name:'Chile',       lon:-71.5, lat:-35.7, type:'fish · salmon',               ships:['us','jp'] },
    { id:'ve', name:'Venezuela',   lon:-66.6, lat:6.4,   type:'shrimp · lobster · octopus',  ships:['us','es'] },
    { id:'pe', name:'Peru',        lon:-75.0, lat:-9.2,  type:'squid · octopus · fish',      ships:['us','es','kr'] },
    { id:'br', name:'Brazil',      lon:-51.9, lat:-14.2, type:'lobster · fish',              ships:['us','eu'] },
    { id:'ar', name:'Argentina',   lon:-63.6, lat:-38.4, type:'squid · fish',                ships:['es','jp','kr'] },
  ];

  // Destinations: USA (primary), plus Europe + Asia
  const destinations = [
    { id:'us', name:'United States',  lon:-95.7, lat:38.0 },
    { id:'eu', name:'European Union', lon:10.4,  lat:51.2 },
    { id:'uk', name:'United Kingdom', lon:-2.4,  lat:54.0 },
    { id:'es', name:'Spain',          lon:-3.7,  lat:40.4 },
    { id:'jp', name:'Japan',          lon:138.3, lat:36.2 },
    { id:'kr', name:'South Korea',    lon:127.8, lat:35.9 },
    { id:'sg', name:'Singapore',      lon:103.8, lat:1.3  },
  ];

  // Trading desk marker only — no longer routed through.
  const hub = { lon:-80.2, lat:25.8, name:'Miami HQ' };

  // Build the actual origin→destination flows list
  const destById = Object.fromEntries(destinations.map(d => [d.id, d]));
  const flows = [];
  origins.forEach(o => {
    o.ships.forEach(dId => {
      const d = destById[dId];
      if (d) flows.push({ from:o, to:d, key:`${o.id}-${dId}` });
    });
  });

  // Build smooth arc from origin → hub → destination using quadratic bezier
  const arc = (a, b) => {
    const [ax, ay] = proj(a.lon, a.lat);
    const [bx, by] = proj(b.lon, b.lat);
    // bow upward (or downward if going reverse hemisphere)
    const mx = (ax + bx) / 2;
    const my = (ay + by) / 2;
    const dx = bx - ax, dy = by - ay;
    const dist = Math.sqrt(dx*dx + dy*dy);
    // perpendicular, scaled by distance
    const nx = -dy / dist;
    const ny =  dx / dist;
    const k = Math.min(dist * 0.32, 110);
    const cx = mx + nx * k;
    const cy = my + ny * k;
    return `M ${ax} ${ay} Q ${cx} ${cy} ${bx} ${by}`;
  };

  return (
    <>
      <style>{`
        .reach{
          background:var(--navy);
          color:var(--paper);
          padding:120px 0;
          position:relative;
        }
        .reach .section-head{border-bottom-color:rgba(243,238,227,.2)}
        .reach .section-head h2{color:var(--paper)}
        .reach .section-head .num{color:var(--brass)}
        .reach .section-head .meta{color:rgba(243,238,227,.55)}

        .reach-grid{
          display:grid;
          grid-template-columns:1fr 280px;
          gap:64px;
          margin-top:60px;
          align-items:start;
        }
        .reach-map-wrap{
          position:relative;
          aspect-ratio:2/1;
          background:rgba(255,255,255,.02);
          border:1px solid rgba(243,238,227,.1);
          padding:24px;
        }
        .reach-map-wrap::before{
          /* corner ticks like a chart */
          content:"";position:absolute;top:8px;left:8px;width:14px;height:14px;
          border-top:1px solid var(--brass);border-left:1px solid var(--brass);
        }
        .reach-map-wrap::after{
          content:"";position:absolute;top:8px;right:8px;width:14px;height:14px;
          border-top:1px solid var(--brass);border-right:1px solid var(--brass);
        }
        .reach-map-wrap .corners-bot{position:absolute;left:0;right:0;bottom:0;height:14px}
        .reach-map-wrap .corners-bot::before{
          content:"";position:absolute;bottom:8px;left:8px;width:14px;height:14px;
          border-bottom:1px solid var(--brass);border-left:1px solid var(--brass);
        }
        .reach-map-wrap .corners-bot::after{
          content:"";position:absolute;bottom:8px;right:8px;width:14px;height:14px;
          border-bottom:1px solid var(--brass);border-right:1px solid var(--brass);
        }
        .reach-map svg{display:block;width:100%;height:auto}

        .reach-side{padding-top:8px}
        .reach-side h3{
          font-family:var(--serif);font-style:italic;font-weight:500;
          font-size:28px;line-height:1.05;margin:0 0 18px;color:var(--paper);
        }
        .reach-side p{
          font-size:14px;line-height:1.6;color:rgba(243,238,227,.72);
          font-weight:300;margin:0 0 28px;
        }
        .reach-filters{
          display:flex;flex-direction:column;gap:6px;
          border-top:1px solid rgba(243,238,227,.18);
          padding-top:18px;
        }
        .reach-filters .lbl{
          font-family:var(--mono);font-size:10px;letter-spacing:.18em;
          text-transform:uppercase;color:rgba(243,238,227,.5);margin-bottom:8px;
        }
        .reach-filters button{
          appearance:none;background:transparent;border:0;color:rgba(243,238,227,.78);
          font-family:var(--sans);font-size:13px;text-align:left;
          padding:10px 0;border-bottom:1px solid rgba(243,238,227,.1);
          cursor:pointer;display:flex;align-items:center;justify-content:space-between;
          transition:.2s;
        }
        .reach-filters button:hover{color:var(--paper)}
        .reach-filters button.active{color:var(--brass)}
        .reach-filters button .count{
          font-family:var(--mono);font-size:11px;color:rgba(243,238,227,.4);
        }
        .reach-filters button.active .count{color:var(--brass)}

        .reach-legend{
          display:flex;gap:24px;margin-top:18px;
          font-family:var(--mono);font-size:11px;letter-spacing:.1em;
          text-transform:uppercase;color:rgba(243,238,227,.55);
        }
        .reach-legend .item{display:flex;align-items:center;gap:8px}
        .reach-legend .dot{width:8px;height:8px;border-radius:50%}
        .reach-legend .dot.org{background:var(--brass)}
        .reach-legend .dot.dst{background:var(--paper)}
        .reach-legend .dot.hub{background:var(--paper);box-shadow:0 0 0 3px rgba(243,238,227,.25)}

        @media (max-width:980px){
          .reach-grid{grid-template-columns:1fr;gap:32px}
        }
      `}</style>

      <section id="reach" className="reach">
        <div className="container">
          <div className="section-head">
            <div className="num">§ 02 — Reach</div>
            <h2>From sea to shore,<br/><em>across three markets.</em></h2>
            <div className="meta">
              {origins.length} origin nodes<br/>
              Across three markets
            </div>
          </div>

          <div className="reach-grid">
            <div className="reach-map-wrap">
              <div className="corners-bot" />
              <div className="reach-map">
                <svg viewBox="0 0 1000 500" xmlns="http://www.w3.org/2000/svg">
                  {/* Latitude/longitude grid (very faint) */}
                  <g stroke="rgba(243,238,227,0.06)" strokeWidth="0.5" fill="none">
                    {[0,1,2,3,4].map(i => <line key={'h'+i} x1="0" x2="1000" y1={i*125} y2={i*125}/>)}
                    {[0,1,2,3,4,5,6,7,8].map(i => <line key={'v'+i} y1="0" y2="500" x1={i*125} x2={i*125}/>)}
                  </g>
                  {/* Continent silhouettes — stippled dot matrix */}
                  <ContinentDots />

                  {/* Direct origin → destination arcs.
                      Color encodes destination region:
                       - US        = brass (warm)
                       - Europe    = paper white
                       - Asia      = sea-green */}
                  {flows.map(f => {
                    const dim = active==='americas' ? 0.12
                              : active==='destinations' ? 0.12
                              : 0.6;
                    const isUS = f.to.id === 'us';
                    const isAsia = ['jp','kr','sg'].includes(f.to.id);
                    const stroke = isUS ? 'var(--brass)'
                                 : isAsia ? '#7fb8a4'
                                 : 'rgba(243,238,227,0.85)';
                    return (
                      <path key={'flow-'+f.key}
                            d={arc(f.from, f.to)}
                            fill="none"
                            stroke={stroke}
                            strokeWidth="0.7"
                            strokeOpacity={dim}
                            strokeDasharray="2 3"/>
                    );
                  })}

                  {/* Origin markers */}
                  {origins.map(o => {
                    const [x,y] = proj(o.lon, o.lat);
                    const dim = active==='destinations' ? 0.25 : 1;
                    return (
                      <g key={o.id} opacity={dim}>
                        <circle cx={x} cy={y} r="3.5" fill="var(--brass)"/>
                        <circle cx={x} cy={y} r="7" fill="none" stroke="var(--brass)" strokeOpacity="0.4"/>
                        <text x={x+10} y={y+3}
                              fontFamily="JetBrains Mono, monospace"
                              fontSize="9" fill="var(--brass)"
                              letterSpacing="1">
                          {o.name.toUpperCase()}
                        </text>
                      </g>
                    );
                  })}

                  {/* Destination markers */}
                  {destinations.map(d => {
                    const [x,y] = proj(d.lon, d.lat);
                    const dim = active==='americas' ? 0.25 : 1;
                    return (
                      <g key={d.id} opacity={dim}>
                        <rect x={x-3} y={y-3} width="6" height="6" fill="rgba(243,238,227,0.95)"/>
                        <text x={x+10} y={y+3}
                              fontFamily="JetBrains Mono, monospace"
                              fontSize="9" fill="rgba(243,238,227,0.85)"
                              letterSpacing="1">
                          {d.name.toUpperCase()}
                        </text>
                      </g>
                    );
                  })}

                  {/* Hub: Miami */}
                  {(() => {
                    const [x,y] = proj(hub.lon, hub.lat);
                    return (
                      <g>
                        <circle cx={x} cy={y} r="6" fill="var(--paper)"/>
                        <circle cx={x} cy={y} r="10" fill="none" stroke="var(--paper)" strokeOpacity="0.3"/>
                        <circle cx={x} cy={y} r="14" fill="none" stroke="var(--paper)" strokeOpacity="0.15"/>
                        <text x={x+14} y={y-6}
                              fontFamily="Cormorant Garamond, serif"
                              fontStyle="italic" fontSize="13" fill="var(--paper)">
                          Miami
                        </text>
                        <text x={x+14} y={y+6}
                              fontFamily="JetBrains Mono, monospace"
                              fontSize="8" fill="rgba(243,238,227,0.6)" letterSpacing="1.5">
                          TRADING DESK
                        </text>
                      </g>
                    );
                  })()}
                </svg>
              </div>
              <div className="reach-legend">
                <div className="item"><span className="dot hub"/>HQ</div>
                <div className="item"><span className="dot org"/>Origin</div>
                <div className="item"><span className="dot dst"/>Destination</div>
                <div className="item"><span className="dot" style={{background:'var(--brass)'}}/>→ US</div>
                <div className="item"><span className="dot" style={{background:'rgba(243,238,227,0.85)'}}/>→ EU</div>
                <div className="item"><span className="dot" style={{background:'#7fb8a4'}}/>→ Asia</div>
              </div>
            </div>

            <div className="reach-side">
              <h3>A book of trusted lanes.</h3>
              <p>
                Latin American origins, three destination markets. We source
                from a vetted book of farms and fisheries across the Americas —
                routing product into the United States, Europe, and Asia, with
                every shipment passing through our Miami trading desk.
              </p>

              <div className="reach-filters">
                <div className="lbl">Filter map</div>
                <button className={active==='all'?'active':''} onClick={()=>setActive('all')}>
                  All flows <span className="count">{flows.length}</span>
                </button>
                <button className={active==='americas'?'active':''} onClick={()=>setActive('americas')}>
                  Origins only <span className="count">{origins.length}</span>
                </button>
                <button className={active==='destinations'?'active':''} onClick={()=>setActive('destinations')}>
                  Destinations only <span className="count">{destinations.length}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

// Stippled continent silhouettes. Hand-tuned dot grid covering rough land
// shapes — no real geographic data, just enough to read as a map.
function ContinentDots() {
  // Each continent is a list of [x,y,r?] dots in 1000×500 space.
  // Generated procedurally from rough bounding regions filled with jittered grid.
  const dots = React.useMemo(() => {
    const seed = (s) => () => (s = (s * 9301 + 49297) % 233280) / 233280;
    const rand = seed(7);

    // Each region: bounding poly (approx) + density.
    // We sample a grid and keep points inside loose ellipse shapes per region.
    const regions = [
      // North America
      { cx:230, cy:155, rx:120, ry:90, density:5, jitter:6 },
      { cx:240, cy:230, rx:60,  ry:40, density:5, jitter:5 }, // mexico/central
      // South America
      { cx:310, cy:340, rx:50, ry:90, density:5, jitter:5 },
      // Greenland
      { cx:340, cy:90, rx:35, ry:30, density:6, jitter:5 },
      // Europe
      { cx:510, cy:155, rx:60, ry:40, density:5, jitter:4 },
      // Africa
      { cx:540, cy:300, rx:65, ry:90, density:5, jitter:5 },
      // Middle East / Arabia
      { cx:600, cy:230, rx:35, ry:30, density:5, jitter:4 },
      // Russia / Northern Asia
      { cx:680, cy:130, rx:160, ry:50, density:5, jitter:5 },
      // India
      { cx:720, cy:240, rx:30, ry:40, density:5, jitter:4 },
      // SE Asia / China
      { cx:790, cy:200, rx:60, ry:50, density:5, jitter:5 },
      // Indonesia
      { cx:820, cy:300, rx:50, ry:18, density:5, jitter:5 },
      // Australia
      { cx:870, cy:360, rx:55, ry:35, density:5, jitter:5 },
      // Japan
      { cx:870, cy:200, rx:18, ry:25, density:5, jitter:4 },
    ];
    const out = [];
    regions.forEach(r => {
      for (let x = r.cx - r.rx; x <= r.cx + r.rx; x += r.density){
        for (let y = r.cy - r.ry; y <= r.cy + r.ry; y += r.density){
          // ellipse test
          const dx = (x - r.cx) / r.rx;
          const dy = (y - r.cy) / r.ry;
          if (dx*dx + dy*dy > 1) continue;
          // edge probability for organic feel
          const edge = dx*dx + dy*dy;
          if (rand() < edge * 0.4) continue;
          const jx = (rand() - 0.5) * r.jitter;
          const jy = (rand() - 0.5) * r.jitter;
          out.push([x + jx, y + jy]);
        }
      }
    });
    return out;
  }, []);

  return (
    <g fill="rgba(243,238,227,0.22)">
      {dots.map(([x,y], i) => (
        <circle key={i} cx={x} cy={y} r="1.1" />
      ))}
    </g>
  );
}

window.Reach = Reach;
