// Walk Around Australia — a virtual fundraising challenge page.
// The community logs kilometres and collectively walks the ~35,000 km
// mainland coastline. Centrepiece is an interactive, animated SVG map with
// a hopping kangaroo that follows the coast, landmark stops, and live stats.

// Total mainland coastline distance used for the challenge (approximate).
const WALK_TOTAL_KM = 35000;

// Accurate Australia geometry (real coastline + projected city coordinates),
// baked offline from Natural Earth data into lib/au-geo.js (window.AU_GEO).
const GEO = (typeof window !== 'undefined' && window.AU_GEO) ||
 { land: '', mainland: '', tasmania: '', viewBox: '0 0 1000 800', cities: {} };
const C = GEO.cities;

// Coastal stops, placed at their real projected coordinates. Their position
// along the trail is measured at runtime so the kangaroo passes each one as
// progress advances.
const WALK_PLACES = [
 { id: 'perth',     name: 'Perth',     x: C.perth[0],     y: C.perth[1],     dy: 4,  anchor: 'end'    },
 { id: 'broome',    name: 'Broome',    x: C.broome[0],    y: C.broome[1],    dy: -14, anchor: 'middle' },
 { id: 'darwin',    name: 'Darwin',    x: C.darwin[0],    y: C.darwin[1],    dy: -14, anchor: 'middle' },
 { id: 'cairns',    name: 'Cairns',    x: C.cairns[0],    y: C.cairns[1],    dy: 4,  anchor: 'start'  },
 { id: 'brisbane',  name: 'Brisbane',  x: C.brisbane[0],  y: C.brisbane[1],  dy: 4,  anchor: 'start'  },
 { id: 'sydney',    name: 'Sydney',    x: C.sydney[0],    y: C.sydney[1],    dy: 4,  anchor: 'start'  },
 { id: 'melbourne', name: 'Melbourne', x: C.melbourne[0], y: C.melbourne[1], dy: 20, anchor: 'middle' },
 { id: 'adelaide',  name: 'Adelaide',  x: C.adelaide[0],  y: C.adelaide[1],  dy: 20, anchor: 'middle' },
];

// -- A single landmark/city marker on the map (status dot + label pill). --
function WalkStop({ place, passed, current }) {
 const fill = passed ? '#FFFFFF' : 'transparent';
 const ring = passed ? '#FFFFFF' : '#4A7EC7';
 const w = place.name.length * 7.2 + 16;
 const lx = place.x + (place.anchor === 'end' ? -10 : place.anchor === 'start' ? 10 : 0);
 const ly = place.y + place.dy;
 const rectX = place.anchor === 'end' ? lx - w : place.anchor === 'start' ? lx : lx - w / 2;
 return (
 <g className="walk-pin" style={{ animationDelay: (WALK_PLACES.indexOf(place) * 90) + 'ms' }}>
 <circle cx={place.x} cy={place.y} r="5.5" fill={fill} stroke={ring} strokeWidth="2.5" />
 {current && <circle cx={place.x} cy={place.y} r="5.5" fill="none" stroke="#4A7EC7" strokeWidth="2" className="walk-stop-pulse" />}
 <g transform={`translate(${rectX}, ${ly - 9})`}>
 <rect width={w} height="18" rx="3" fill="rgba(13,27,42,0.78)" />
 <text x={w / 2} y="13" textAnchor="middle" fontSize="11" fontWeight="700"
 fill="#FFFFFF" style={{ letterSpacing: '0.02em' }}>{place.name}</text>
 </g>
 </g>
 );
}

// -- Sydney Opera House: three sails, drawn small in white. --
function OperaHouse({ x, y }) {
 return (
 <g transform={`translate(${x}, ${y})`} aria-hidden="true">
 <path d="M -14 6 Q -10 -10 -3 6 Z" fill="#FFFFFF" />
 <path d="M -5 6 Q 0 -13 6 6 Z" fill="#FFFFFF" />
 <path d="M 4 6 Q 9 -8 14 6 Z" fill="#F7F4F0" />
 <rect x="-15" y="6" width="30" height="2.5" fill="#D5CFBF" />
 </g>
 );
}

// -- Uluru: a sandstone dome in the red centre (warm neutral, on-brand). --
function Uluru({ x, y }) {
 return (
 <g transform={`translate(${x}, ${y})`}>
 <path d="M -22 8 Q -18 -7 0 -9 Q 20 -8 22 8 Z" fill="#B8B2A8" stroke="#8E7F6E" strokeWidth="1" />
 <path d="M -22 8 Q -18 -7 0 -9 Q 20 -8 22 8" fill="none" stroke="rgba(255,255,255,0.25)" strokeWidth="1" />
 <g transform="translate(0, 20)">
 <rect x="-20" y="-9" width="40" height="17" rx="3" fill="rgba(13,27,42,0.78)" />
 <text x="0" y="3" textAnchor="middle" fontSize="11" fontWeight="700" fill="#FFFFFF">Uluru</text>
 </g>
 </g>
 );
}

function WalkPage({ navigate }) {
 const reduce = typeof window !== 'undefined' && window.matchMedia
 && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

 const trailRef = React.useRef(null);
 const [length, setLength] = React.useState(0);
 const [stops, setStops] = React.useState(WALK_PLACES.map(p => ({ ...p, frac: 0 })));
 const [roo, setRoo] = React.useState({ x: C.perth ? C.perth[0] : 285, y: C.perth ? C.perth[1] : 349 });
 const [progress, setProgress] = React.useState(0.34);
 const [playing, setPlaying] = React.useState(!reduce);

 // Measure the trail once it is in the DOM, and place each stop at the
 // nearest point along the path so the kangaroo passes it at that progress.
 React.useEffect(() => {
 const path = trailRef.current;
 if (!path) return;
 const len = path.getTotalLength();
 setLength(len);
 const N = 720;
 const samples = [];
 for (let i = 0; i <= N; i++) samples.push(path.getPointAtLength((len * i) / N));
 setStops(WALK_PLACES.map(p => {
 let best = 0, bestD = Infinity;
 for (let i = 0; i <= N; i++) {
 const d = (samples[i].x - p.x) ** 2 + (samples[i].y - p.y) ** 2;
 if (d < bestD) { bestD = d; best = i; }
 }
 return { ...p, frac: best / N };
 }));
 }, []);

 // Move the kangaroo to the current point on the trail.
 React.useEffect(() => {
 const path = trailRef.current;
 if (!path || !length) return;
 const p = path.getPointAtLength(length * Math.min(progress, 0.9999));
 setRoo({ x: p.x, y: p.y });
 }, [progress, length]);

 // Auto-walk: advance progress smoothly so the country fills in.
 React.useEffect(() => {
 if (!playing) return;
 let raf, last = performance.now();
 const tick = (now) => {
 const dt = (now - last) / 1000; last = now;
 setProgress(p => { const np = p + dt * 0.05; return np >= 1 ? 0 : np; });
 raf = requestAnimationFrame(tick);
 };
 raf = requestAnimationFrame(tick);
 return () => cancelAnimationFrame(raf);
 }, [playing]);

 const km = Math.round(progress * WALK_TOTAL_KM);
 const pct = Math.round(progress * 100);
 const next = stops.filter(s => s.frac > progress).sort((a, b) => a.frac - b.frac)[0];
 const dash = length || 1;

 return (
 <div data-screen-label="Walk Around Australia">
 <PageHero
 eyebrow="Get Involved · Fundraising challenge"
 title="Walk Around Australia for SCN2A"
 body="Lace up, log your kilometres, and help our community walk the full coastline of Australia, about 35,000 km, together. Every step raises funds for research and the families navigating SCN2A."
 accent="coral"
 ledger={["MAINLAND COASTLINE · ~35,000 KM", "EVERY STATE & TERRITORY", "WALK · RUN · ROLL · EVERY DISTANCE COUNTS"]}
 primaryCta={{ label: 'Join the walk', onClick: () => navigate('involved') }}
 secondaryCta={{ label: 'How it works', onClick: () => { const el = document.getElementById('walk-how'); if (el) el.scrollIntoView({ behavior: 'smooth' }); } }}
 navigate={navigate} />

 <Breadcrumbs items={[{ label: 'Get Involved', to: 'involved' }, { label: 'Walk Around Australia' }]} navigate={navigate} />

 {/* Interactive map — the navy feature band for this page */}
 <section style={{ background: '#1E3A6E', color: '#fff', padding: '72px 0', position: 'relative', overflow: 'hidden' }}>
 <div className="container" style={{ position: 'relative' }}>
 <div style={{ maxWidth: 760, marginBottom: 36 }}>
 <div className="eyebrow" style={{ color: '#D8C2CD' }}>The challenge</div>
 <h2 className="h2-mobile" style={{ fontSize: 'clamp(28px, 3.4vw, 40px)', fontWeight: 700, color: '#fff', margin: '12px 0 14px', lineHeight: 1.15, letterSpacing: '-0.01em' }}>
 Watch the nation move, one step at a time.
 </h2>
 <p style={{ fontSize: 17, lineHeight: 1.6, margin: 0, color: 'rgba(255,255,255,0.9)', maxWidth: 620 }}>
 Every kilometre the community logs carries our kangaroo further around the
 coast, past every state and territory, and home again. Drag the slider to
 preview the journey, or let it walk.
 </p>
 </div>

 <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 40, alignItems: 'start' }} className="stack-mobile">

 {/* The map */}
 <div style={{ position: 'relative' }}>
 <svg viewBox={GEO.viewBox} width="100%" role="img"
 aria-label={`Map of Australia showing a coastal walking route. The community has walked ${km.toLocaleString()} of ${WALK_TOTAL_KM.toLocaleString()} kilometres, ${pct} percent of the way around.`}
 style={{ display: 'block' }}>
 {/* Southern Cross, twinkling in the Tasman/Coral Sea */}
 <g fill="#4A7EC7" aria-hidden="true">
 {[[918, 430, 4], [948, 472, 3], [906, 502, 3.4], [882, 470, 2.6], [932, 548, 2.2]].map((s, i) => (
 <circle key={i} cx={s[0]} cy={s[1]} r={s[2]} className="walk-twinkle" style={{ animationDelay: (i * 0.5) + 's' }} />
 ))}
 </g>

 {/* Land — accurate coastline (mainland + Tasmania + islands) */}
 <path d={GEO.land} fill="#EFEAE2" stroke="rgba(255,255,255,0.45)" strokeWidth="1" fillRule="evenodd" />

 {/* Remaining route — faint dotted marching ants along the real coastline */}
 <path d={GEO.mainland} fill="none" stroke="rgba(255,255,255,0.4)"
 strokeWidth="1.4" strokeDasharray="1.5 7" strokeLinecap="round"
 className={reduce ? '' : 'walk-ants'} />

 {/* Walked route — bright, revealed by progress */}
 <path ref={trailRef} d={GEO.mainland} fill="none" stroke="#FFFFFF"
 strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round"
 style={{ strokeDasharray: dash, strokeDashoffset: dash * (1 - progress), transition: 'stroke-dashoffset 400ms ease', filter: 'drop-shadow(0 0 3px rgba(74,126,199,0.9))' }} />

 {/* Inland landmarks */}
 <Uluru x={C.uluru[0]} y={C.uluru[1]} />
 <OperaHouse x={C.sydney[0]} y={C.sydney[1] - 13} />
 <text x={608} y={332} fontSize="24" textAnchor="middle" aria-hidden="true" className="walk-bob">🐨</text>
 <g transform={`translate(${C.hobart[0] + 44}, ${C.hobart[1] - 8})`}>
 <rect x="-26" y="-9" width="52" height="17" rx="3" fill="rgba(13,27,42,0.78)" />
 <text x="0" y="3" textAnchor="middle" fontSize="11" fontWeight="700" fill="#FFFFFF">Tasmania</text>
 </g>

 {/* Coastal stops */}
 {stops.map(s => (
 <WalkStop key={s.id} place={s} passed={progress >= s.frac} current={next && next.id === s.id} />
 ))}

 {/* The kangaroo, hopping along the coast */}
 <g style={{ transform: `translate(${roo.x}px, ${roo.y}px)` }}>
 <circle r="13" fill="#4A7EC7" opacity="0.25" className={reduce ? '' : 'walk-roo-pulse'} />
 <text y="5" fontSize="30" textAnchor="middle" aria-hidden="true" className={reduce ? '' : 'walk-roo-hop'}>🦘</text>
 </g>

 {/* Compass */}
 <g transform="translate(930, 150)" aria-hidden="true">
 <circle r="22" fill="rgba(13,27,42,0.5)" stroke="rgba(255,255,255,0.6)" strokeWidth="1.5" />
 <path d="M 0 -15 L 5 2 L 0 -3 L -5 2 Z" fill="#FFFFFF" />
 <path d="M 0 15 L 5 -2 L 0 3 L -5 -2 Z" fill="rgba(255,255,255,0.5)" />
 <text y="-25" textAnchor="middle" fontSize="12" fontWeight="700" fill="#FFFFFF">N</text>
 </g>
 </svg>
 </div>

 {/* Control + stats panel — a warm-white card on the navy band */}
 <div style={{ background: '#F7F4F0', borderRadius: 5, padding: '28px 28px 30px', color: '#0D1B2A' }}>
 <div className="eyebrow" style={{ color: '#6B6659' }}>Community progress</div>
 <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 10 }}>
 <div className="ledger-mono" style={{ fontSize: 44, fontWeight: 800, color: '#1E3A6E', lineHeight: 1, letterSpacing: '-0.02em' }}>{km.toLocaleString()}</div>
 <div style={{ fontSize: 15, fontWeight: 700, color: '#6B6659' }}>km</div>
 </div>
 <div style={{ fontSize: 14, color: '#6B6659', marginTop: 6 }}>
 of {WALK_TOTAL_KM.toLocaleString()} km · {pct}% around the coastline
 </div>

 {/* Progress bar */}
 <div style={{ height: 8, background: '#E8E3DA', borderRadius: 4, marginTop: 16, overflow: 'hidden' }}>
 <div style={{ height: '100%', width: pct + '%', background: '#1E3A6E', borderRadius: 4, transition: 'width 400ms ease' }} />
 </div>

 {/* Slider */}
 <label style={{ display: 'block', marginTop: 20 }}>
 <span style={{ fontSize: 13, fontWeight: 700 }}>Preview the journey</span>
 <input type="range" min="0" max="1000" value={Math.round(progress * 1000)}
 onChange={(e) => { setPlaying(false); setProgress(Number(e.target.value) / 1000); }}
 style={{ width: '100%', marginTop: 10, accentColor: '#1E3A6E', height: 24, cursor: 'pointer' }}
 aria-label="Kilometres walked around Australia" />
 </label>

 <button onClick={() => setPlaying(p => !p)} aria-pressed={playing}
 style={{
 marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 8,
 minHeight: 44, padding: '10px 18px', fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
 background: '#fff', color: '#0D1B2A', border: '1.5px solid #D5CFBF', borderRadius: 5, cursor: 'pointer',
 }}>
 <i data-lucide={playing ? 'pause' : 'play'} style={{ width: 16, height: 16 }} />
 {playing ? 'Pause the walk' : 'Walk the route'}
 </button>

 {next && (
 <div style={{ marginTop: 18, padding: '12px 16px', background: '#fff', borderLeft: '4px solid #4A7EC7', fontSize: 14, lineHeight: 1.5 }}>
 <strong>Next stop:</strong> {next.name}, {Math.max(0, Math.round((next.frac - progress) * WALK_TOTAL_KM)).toLocaleString()} km to go.
 </div>
 )}

 {/* Milestone list */}
 <ul style={{ listStyle: 'none', padding: 0, margin: '20px 0 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px 16px' }}>
 {stops.map(s => {
 const done = progress >= s.frac;
 return (
 <li key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: done ? '#0D1B2A' : '#6B6659', fontWeight: done ? 700 : 500 }}>
 <i data-lucide={done ? 'check-circle-2' : 'circle'} style={{ width: 15, height: 15, color: done ? '#1E3A6E' : '#B8B2A8', flexShrink: 0 }} />
 {s.name}
 </li>
 );
 })}
 </ul>
 </div>
 </div>
 </div>
 </section>

 {/* How it works */}
 <div id="walk-how">
 <SubsectionGrid
 eyebrow="How it works"
 title="Three steps to put SCN2A on the map."
 body="Walk, run, push or roll. Any distance counts, anywhere in the country, on your own or as a team."
 items={[
 { icon: 'user-plus', title: 'Sign up and set a goal', body: 'Register your walk, set a personal or team target, and get a fundraising page in minutes.', cta: 'Register', coral: true },
 { icon: 'footprints', title: 'Log every kilometre', body: 'Record your distance after each walk and watch it add to the national total in real time.', cta: 'See the tracker', coral: true },
 { icon: 'map', title: 'Move the map', body: 'Each kilometre carries the community further around the coast, past every capital and home again.', cta: 'View the route', coral: true },
 ]}
 navigate={navigate}
 accent="coral" />
 </div>

 {/* Why it matters band */}
 <section style={{ background: '#E8E3DA', padding: '72px 0' }}>
 <div className="container">
 <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }} className="stack-mobile-2">
 {[
 { stat: '~35,000', unit: 'km of coastline', body: 'The distance our community is walking together, end to end.' },
 { stat: '1 in 100', unit: 'live births carry a DEE', body: 'Developmental and epileptic encephalopathies are more common than most realise.' },
 { stat: '100%', unit: 'stays in Australia', body: 'Funds raised support local research partnerships and family navigation.' },
 ].map((c, i) => (
 <div key={i} style={{ background: '#fff', border: '1px solid #D5CFBF', borderRadius: 5, padding: '26px 24px' }}>
 <div className="ledger-mono" style={{ fontSize: 34, fontWeight: 800, color: '#1E3A6E', lineHeight: 1 }}>{c.stat}</div>
 <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#6B6659', marginTop: 8 }}>{c.unit}</div>
 <p style={{ fontSize: 15, lineHeight: 1.6, color: '#0D1B2A', margin: '12px 0 0' }}>{c.body}</p>
 </div>
 ))}
 </div>
 </div>
 </section>

 <CTABlock
 eyebrow="Ready when you are"
 title="Start your team and walk for SCN2A."
 body="Gather a few friends, set a target, and we will send you everything you need: a fundraising page, a kit, and a community cheering you on around the whole country."
 ctaLabel="Join the walk"
 onCta={() => navigate('involved')}
 secondaryLabel="Talk to us"
 onSecondary={() => navigate('contact')} />
 </div>
 );
}

Object.assign(window, { WalkPage });
