// Node network — scattered nodes with delaunay-ish connections
// Trade-route ports — global APAC-centric map (600 x 460 viewBox).
// Projection: x = ((lng - 50 + 360) mod 360) * 1.76    (50°E → ~250°E west reach across Pacific)
//             y = (60 - lat) * 4.6                      (+60°N → -40°S)
const NETWORK_NODES = [
  // East Asia / China
  { x: 113, y: 174, w: 1,    city: 'Hong Kong' },                    // 0  HUB
  { x: 126, y: 132, w: 0.6,  city: 'Shanghai' },                     // 1
  { x: 117, y: 93,  w: 0.55, city: 'Beijing',     align: 'left' },   // 2
  { x: 159, y: 111, w: 0.55, city: 'Tokyo' },                        // 3
  { x: 135, y: 104, w: 0.5,  city: 'Seoul',       align: 'top' },    // 4
  // South East Asia
  { x: 89,  y: 213, w: 0.5,  city: 'Bangkok',     align: 'left' },   // 5
  { x: 125, y: 209, w: 0.5,  city: 'Manila' },                       // 6
  { x: 88,  y: 263, w: 0.5,  city: 'Kuala Lumpur', align: 'left' },  // 7
  { x: 95,  y: 270, w: 0.55, city: 'Singapore',   align: 'bottom' }, // 8
  { x: 100, y: 304, w: 0.5,  city: 'Jakarta' },                      // 9
  // Middle East
  { x: 9,   y: 160, w: 0.55, city: 'Dubai' },                        // 10
  // South Pacific / Oceania
  { x: 224, y: 358, w: 0.45, city: 'Fiji' },                         // 11
  { x: 178, y: 432, w: 1,    city: 'Sydney' },                       // 12 HQ
  { x: 167, y: 450, w: 0.5,  city: 'Melbourne',   align: 'left' },   // 13
  { x: 220, y: 446, w: 0.45, city: 'Auckland' },                     // 14
  // North America
  { x: 330, y: 58,  w: 0.5,  city: 'Seattle' },                      // 15
  { x: 338, y: 120, w: 0.6,  city: 'Los Angeles', align: 'left' },   // 16
  { x: 415, y: 89,  w: 0.6,  city: 'New York' },                     // 17
  { x: 404, y: 157, w: 0.5,  city: 'Miami',       align: 'left' },   // 18
  // Europe
  { x: 545, y: 35,  w: 0.55, city: 'London',      align: 'top' },    // 19
  { x: 552, y: 58,  w: 0.5,  city: 'Paris',       align: 'left' },   // 20
  { x: 568, y: 42,  w: 0.5,  city: 'Frankfurt' },                    // 21
  { x: 575, y: 82,  w: 0.5,  city: 'Rome' },                         // 22
];

// SYD is origin → HKG is hub. HKG fans out globally.
const NETWORK_EDGES = [
  [12, 0],  // SYD → HKG (primary artery)
  // HKG → East Asia
  [0, 1],   // HKG → PVG
  [0, 2],   // HKG → PEK
  [0, 3],   // HKG → NRT
  [0, 4],   // HKG → ICN
  // HKG → SEA
  [0, 5],   // HKG → BKK
  [0, 6],   // HKG → MNL
  [0, 7],   // HKG → KUL
  [0, 8],   // HKG → SIN
  [0, 9],   // HKG → CGK
  // HKG → Middle East
  [0, 10],  // HKG → DXB
  // HKG → Pacific
  [0, 11],  // HKG → NAN (Fiji)
  [0, 14],  // HKG → AKL
  // HKG → North America
  [0, 15],  // HKG → SEA
  [0, 16],  // HKG → LAX
  [0, 17],  // HKG → JFK
  [0, 18],  // HKG → MIA
  // HKG → Europe
  [0, 19],  // HKG → LHR
  [0, 20],  // HKG → CDG
  [0, 21],  // HKG → FRA
  [0, 22],  // HKG → FCO
  // SYD feeders
  [12, 13], // SYD → MEL (domestic)
  [12, 16], // SYD → LAX (trans-Pacific direct)
];

// Network — dark-mode institutional schematic: APAC closed-loop ecosystem
const Network = () => {
  // Stat strip — verifiable numbers derived from the page itself.
  const statsRef = React.useRef(null);
  React.useEffect(() => {
    const root = statsRef.current;
    if (!root) return;
    const animate = (el) => {
      const target = parseFloat(el.dataset.target);
      const suffix = el.dataset.suffix || '';
      const dur = parseInt(el.dataset.dur, 10) || 1800;
      const start = performance.now();
      const ease = (t) => 1 - Math.pow(1 - t, 3);
      const tick = (now) => {
        const t = Math.min(1, (now - start) / dur);
        const v = Math.round(target * ease(t));
        el.textContent = v + suffix;
        if (t < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          root.querySelectorAll('.gb-net2__stat-k').forEach(animate);
          io.disconnect();
        }
      });
    }, { threshold: 0.3 });
    io.observe(root);
    return () => io.disconnect();
  }, []);

  // Schematic: BRANDS (origin) → HK FREE-TRADE HUB → DISTRIBUTION → END MARKETS
  // Rendered as an SVG flow-diagram placeholder; user will replace with branded asset.
  return (
    <section className="gb-section gb-section--ink gb-net2" id="network">
      <div className="gb-container">

        <div className="gb-net2__head">
          <span className="gb-her2__eyebrow gb-net2__eyebrow">— III. NETWORK</span>
          <div className="gb-net2__beam" aria-hidden="true">
            <svg className="gb-net2__beam-svg" viewBox="0 0 600 460" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="gb-beam-grad" x1="0%" y1="0%" x2="100%" y2="0%">
                  <stop offset="0%"   stopColor="rgba(201,168,107,0)"/>
                  <stop offset="35%"  stopColor="rgba(201,168,107,0.55)"/>
                  <stop offset="50%"  stopColor="rgba(245,225,170,1)"/>
                  <stop offset="65%"  stopColor="rgba(201,168,107,0.55)"/>
                  <stop offset="100%" stopColor="rgba(201,168,107,0)"/>
                </linearGradient>
                <filter id="gb-beam-soft" x="-20%" y="-20%" width="140%" height="140%">
                  <feGaussianBlur stdDeviation="0.5"/>
                </filter>
              </defs>

              {/* Trade routes — great-circle style arcs (always bowed toward top). */}
              {(() => {
                const arcs = NETWORK_EDGES.map(([a, b], i) => {
                  const A = NETWORK_NODES[a], B = NETWORK_NODES[b];
                  const mx = (A.x + B.x) / 2, my = (A.y + B.y) / 2;
                  const dx = B.x - A.x, dy = B.y - A.y;
                  const len = Math.hypot(dx, dy) || 1;
                  // perpendicular, but always bow UPWARD (negative y) — like great-circle routes on a flat map
                  let nx = -dy / len, ny = dx / len;
                  if (ny > 0) { nx = -nx; ny = -ny; }
                  const bow = Math.min(95, len * 0.32);
                  const cx = mx + nx * bow;
                  const cy = my + ny * bow;
                  return { d: `M ${A.x} ${A.y} Q ${cx} ${cy} ${B.x} ${B.y}`, len, A, B };
                });
                return (
                  <React.Fragment>
                    {/* Static dashed route lines (faint) */}
                    {arcs.map((e, i) => (
                      <path key={`r${i}`} d={e.d}
                            fill="none" stroke="rgba(245,243,238,0.16)"
                            strokeWidth="0.7" strokeDasharray="2 3" strokeLinecap="round"/>
                    ))}
                    {/* Animated golden vessel trails */}
                    {arcs.map((e, i) => (
                      <path key={`f${i}`} d={e.d}
                            className="gb-net2__beam-flow"
                            fill="none"
                            stroke="url(#gb-beam-grad)" strokeWidth="1.7"
                            filter="url(#gb-beam-soft)"
                            pathLength="100" strokeDasharray="30 70" strokeDashoffset="0"
                            strokeLinecap="round"
                            style={{ animationDelay: `${-(i * 0.4)}s`, animationDuration: `${4 + (i % 4) * 0.9}s` }}/>
                    ))}
                    {/* Moving vessel dot riding each arc */}
                    {arcs.map((e, i) => (
                      <circle key={`v${i}`} r="1.9"
                              fill="rgba(245,225,170,1)"
                              filter="url(#gb-beam-soft)">
                        <animateMotion
                          dur={`${4.5 + (i % 5) * 1}s`}
                          repeatCount="indefinite"
                          begin={`${-(i * 0.4)}s`}
                          path={e.d}
                          rotate="auto"/>
                      </circle>
                    ))}
                  </React.Fragment>
                );
              })()}

              {/* Ports — dual-ring markers with city-name labels */}
              {NETWORK_NODES.map((n, i) => {
                const isHub = n.w >= 1;
                const r1 = 2 + n.w * 2.5;
                const r2 = 5 + n.w * 5;
                const align = n.align || 'right';
                let tx = n.x + r2 + 5, ty = n.y + 3, anchor = 'start';
                if (align === 'left')   { tx = n.x - r2 - 5; ty = n.y + 3; anchor = 'end'; }
                if (align === 'top')    { tx = n.x;          ty = n.y - r2 - 5; anchor = 'middle'; }
                if (align === 'bottom') { tx = n.x;          ty = n.y + r2 + 11; anchor = 'middle'; }
                return (
                  <g key={`n${i}`}>
                    {isHub && (
                      <circle cx={n.x} cy={n.y} r={r2 + 4}
                              fill="none" stroke="rgba(201,168,107,0.45)" strokeWidth="0.6"
                              className="gb-net2__pulse"/>
                    )}
                    <circle cx={n.x} cy={n.y} r={r2}
                            fill="none" stroke="rgba(201,168,107,0.6)" strokeWidth="0.7"/>
                    <circle cx={n.x} cy={n.y} r={r1}
                            fill={isHub ? 'rgba(245,225,170,1)' : 'rgba(201,168,107,0.9)'}/>
                    <text x={tx} y={ty} textAnchor={anchor}
                          fill={isHub ? 'rgba(245,225,170,1)' : 'rgba(245,243,238,0.78)'}
                          fontFamily="'Inter Tight', system-ui, sans-serif"
                          fontWeight={isHub ? 500 : 400}
                          fontSize="9" letterSpacing="0.04em">
                      {n.city}
                    </text>
                  </g>
                );
              })}
            </svg>
          </div>
          <h2 className="gb-net2__title">
            Dominant APAC <em>distribution artery</em>.
          </h2>
          <p className="gb-net2__lead">
            A proprietary, institutional-grade placement network engineered for volume.
            Anchored by our strategically positioned free-trade operations in Hong Kong,
            our infrastructure orchestrates the frictionless flow of high-value assets
            deep into priority markets. Total channel control — eliminating traditional
            supply-chain vulnerabilities and strictly insulating operations from external
            disruptions.
          </p>
        </div>

        {/* Container yard — APAC distribution artery */}
        <div className="gb-net2__schematic">
          <div className="gb-net2__photo">
            <img src="assets/warehouse.png?v=2" alt="Goodbrand Group warehouse — distribution artery"/>
          </div>

          <svg className="gb-net2__svg" viewBox="0 0 1200 720" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" style={{ display: 'none' }}>
            <defs>
              <radialGradient id="gb-radar-fade" cx="50%" cy="50%" r="50%">
                <stop offset="0%" stopColor="rgba(201,168,107,0.10)"/>
                <stop offset="60%" stopColor="rgba(201,168,107,0.02)"/>
                <stop offset="100%" stopColor="rgba(201,168,107,0)"/>
              </radialGradient>
              <linearGradient id="gb-radar-sweep" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" stopColor="rgba(201,168,107,0)"/>
                <stop offset="40%" stopColor="rgba(201,168,107,0)"/>
                <stop offset="95%" stopColor="rgba(201,168,107,0.55)"/>
                <stop offset="100%" stopColor="rgba(201,168,107,0.85)"/>
              </linearGradient>
              <pattern id="gb-grid" width="48" height="48" patternUnits="userSpaceOnUse">
                <path d="M 48 0 L 0 0 0 48" fill="none" stroke="rgba(245,243,238,0.04)" strokeWidth="1"/>
              </pattern>
              <filter id="gb-glow" x="-50%" y="-50%" width="200%" height="200%">
                <feGaussianBlur stdDeviation="3" result="b"/>
                <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
              </filter>
            </defs>

            {/* Background grid */}
            <rect x="0" y="0" width="1200" height="720" fill="url(#gb-grid)"/>

            {/* Center coordinates: 600, 360 */}
            {/* Cross-hairs */}
            <line x1="60" y1="360" x2="1140" y2="360" stroke="rgba(245,243,238,0.05)" strokeWidth="1" strokeDasharray="2 6"/>
            <line x1="600" y1="40" x2="600" y2="680" stroke="rgba(245,243,238,0.05)" strokeWidth="1" strokeDasharray="2 6"/>

            {/* Soft inner glow */}
            <circle cx="600" cy="360" r="320" fill="url(#gb-radar-fade)"/>

            {/* Three concentric rings — TRANSIT (inner) / DISTRIBUTION / MARKET (outer) */}
            <circle cx="600" cy="360" r="120" fill="none" stroke="rgba(201,168,107,0.55)" strokeWidth="1"/>
            <circle cx="600" cy="360" r="220" fill="none" stroke="rgba(245,243,238,0.18)" strokeWidth="1" strokeDasharray="3 5"/>
            <circle cx="600" cy="360" r="320" fill="none" stroke="rgba(245,243,238,0.12)" strokeWidth="1" strokeDasharray="2 7"/>

            {/* Ring labels (top) */}
            <text x="600" y="232" textAnchor="middle" fill="rgba(201,168,107,0.85)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="2">— RING 01 · TRANSIT</text>
            <text x="600" y="132" textAnchor="middle" fill="rgba(245,243,238,0.45)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="2">— RING 02 · DISTRIBUTION</text>
            <text x="600" y="32" textAnchor="middle" fill="rgba(245,243,238,0.35)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="2">— RING 03 · MARKET</text>

            {/* Sweep line — slow rotation (CSS animation on group) */}
            <g className="gb-net2__sweep" style={{ transformOrigin: '600px 360px' }}>
              <path d="M 600 360 L 920 360 A 320 320 0 0 0 855 165 Z" fill="url(#gb-radar-sweep)" opacity="0.55"/>
              <line x1="600" y1="360" x2="920" y2="360" stroke="rgba(201,168,107,0.85)" strokeWidth="1"/>
            </g>

            {/* HK center node */}
            <g>
              <circle cx="600" cy="360" r="28" fill="none" stroke="rgba(201,168,107,0.85)" strokeWidth="1.4"/>
              <circle cx="600" cy="360" r="6" fill="rgba(201,168,107,1)" filter="url(#gb-glow)"/>
              <circle cx="600" cy="360" r="3" fill="#F5F3EE"/>
              <text x="600" y="412" textAnchor="middle" fill="rgba(201,168,107,1)" fontFamily="ui-monospace, monospace" fontSize="11" letterSpacing="2.5">HKG · CONTROL NODE</text>
              <text x="600" y="432" textAnchor="middle" fill="rgba(245,243,238,0.55)" fontFamily="serif" fontSize="11" fontStyle="italic">Free-trade fulcrum · 22.32°N 114.17°E</text>
            </g>

            {/* Ring 01 — TRANSIT inner ring nodes (operational functions) */}
            {[
              { a: -60, t: 'SECURE TRANSIT' },
              { a: 60,  t: 'INVENTORY ORCHESTRATION' },
              { a: 180, t: 'AUDIT-READY COMPLIANCE' },
            ].map((n, i) => {
              const rad = (n.a * Math.PI) / 180;
              const x = 600 + 120 * Math.cos(rad);
              const y = 360 + 120 * Math.sin(rad);
              const tx = 600 + 144 * Math.cos(rad);
              const ty = 360 + 144 * Math.sin(rad);
              const anchor = Math.cos(rad) > 0.3 ? 'start' : Math.cos(rad) < -0.3 ? 'end' : 'middle';
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r="4" fill="rgba(201,168,107,0.85)"/>
                  <text x={tx} y={ty + 4} textAnchor={anchor} fill="rgba(245,243,238,0.7)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="1.8">{n.t}</text>
                </g>
              );
            })}

            {/* Ring 02 — DISTRIBUTION (SEA boutiques + OCE institutional) */}
            {[
              { a: -110, t: 'SEA · INDEPENDENT', sub: 'Boutique network' },
              { a: -40,  t: 'OCE · INSTITUTIONAL', sub: 'Procurement programmes' },
              { a: 50,   t: 'NEA · STRATEGIC', sub: 'Partner placements' },
            ].map((n, i) => {
              const rad = (n.a * Math.PI) / 180;
              const x = 600 + 220 * Math.cos(rad);
              const y = 360 + 220 * Math.sin(rad);
              const tx = 600 + 244 * Math.cos(rad);
              const ty = 360 + 244 * Math.sin(rad);
              const anchor = Math.cos(rad) > 0.3 ? 'start' : Math.cos(rad) < -0.3 ? 'end' : 'middle';
              return (
                <g key={i}>
                  <line x1="600" y1="360" x2={x} y2={y} stroke="rgba(201,168,107,0.20)" strokeWidth="0.8"/>
                  <circle cx={x} cy={y} r="5" fill="none" stroke="rgba(201,168,107,0.85)" strokeWidth="1.2"/>
                  <circle cx={x} cy={y} r="2" fill="rgba(201,168,107,1)"/>
                  <text x={tx} y={ty - 2} textAnchor={anchor} fill="#F5F3EE" fontFamily="ui-monospace, monospace" fontSize="11" letterSpacing="1.5">{n.t}</text>
                  <text x={tx} y={ty + 14} textAnchor={anchor} fill="rgba(245,243,238,0.5)" fontFamily="serif" fontSize="11" fontStyle="italic">{n.sub}</text>
                </g>
              );
            })}

            {/* Ring 03 — MARKET (end cities) */}
            {[
              { a: -150, t: 'SG' },
              { a: -125, t: 'KL' },
              { a: -95,  t: 'BKK' },
              { a: -70,  t: 'JKT' },
              { a: -25,  t: 'MNL' },
              { a: 15,   t: 'AU' },
              { a: 40,   t: 'NZ' },
              { a: 80,   t: 'TPE' },
              { a: 110,  t: 'TYO' },
              { a: 140,  t: 'SEL' },
            ].map((n, i) => {
              const rad = (n.a * Math.PI) / 180;
              const x = 600 + 320 * Math.cos(rad);
              const y = 360 + 320 * Math.sin(rad);
              const tx = 600 + 340 * Math.cos(rad);
              const ty = 360 + 340 * Math.sin(rad);
              const anchor = Math.cos(rad) > 0.3 ? 'start' : Math.cos(rad) < -0.3 ? 'end' : 'middle';
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r="3" fill="rgba(245,243,238,0.85)"/>
                  <text x={tx} y={ty + 4} textAnchor={anchor} fill="rgba(245,243,238,0.65)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="1.8">{n.t}</text>
                </g>
              );
            })}

            {/* Footer ticks */}
            <line x1="60" y1="680" x2="1140" y2="680" stroke="rgba(245,243,238,0.12)" strokeWidth="1"/>
            <text x="60" y="700" fill="rgba(245,243,238,0.45)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="1.5">REV. 2026.04 · GBG/NET · POLAR PROJECTION</text>
            <text x="1140" y="700" textAnchor="end" fill="rgba(245,243,238,0.45)" fontFamily="ui-monospace, monospace" fontSize="10" letterSpacing="1.5">CONFIDENTIAL</text>
          </svg>
        </div>

        {/* Stat strip below schematic — animated counters with verifiable numbers */}
        <div className="gb-net2__stats" ref={statsRef}>
          {[
            { k: 40,  suffix: '+',  dur: 1900, kicker: 'PREMIUM LABELS',  l: 'Brand families managed' },
            { k: 18,  suffix: '',   dur: 1800, kicker: 'TRADE LANES',     l: 'APAC distribution corridors' },
            { k: 120, suffix: '+',  dur: 2400, kicker: 'PARTNER NETWORK', l: 'Independent + institutional' },
            { k: 100, suffix: '%',  dur: 2000, kicker: 'VERIFIED SUPPLY', l: 'Multi-tier sourcing · Audit-ready' },
          ].map((s, i) => (
            <div key={i} className="gb-net2__stat">
              <div style={{fontSize:'11px', letterSpacing:'0.22em', textTransform:'uppercase', color:'rgba(201,168,107,0.85)', fontWeight:500, marginBottom:12}}>— {s.kicker}</div>
              <div className="gb-net2__stat-k" data-target={s.k} data-suffix={s.suffix} data-dur={s.dur} style={{fontFamily:'var(--font-display)', fontSize:'44px', fontWeight:200, lineHeight:1, color:'#F5F3EE', letterSpacing:'-0.03em', marginBottom:10}}>0{s.suffix}</div>
              <div className="gb-net2__stat-l" style={{fontSize:'12px', color:'rgba(245,243,238,0.6)', lineHeight:1.5, fontStyle:'italic'}}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};
window.Network = Network;
