// ROAMR — Plan, AI Builder, GPX Health Check, Navigation, Pricing
const { TOKENS: P_T, Chip: P_Chip, ConfBadge: P_Conf, Stat: P_Stat, SurfaceBar: P_SB, MapMock: P_Map, ElevationGraph: P_Elev, ActIcon: P_Act, SectionHead: P_SH, IconBtn: P_IB } = window;

// ────────────────────────────────────────────────────────────
// PLAN HUB
// ────────────────────────────────────────────────────────────
function PlanScreen({ onNavigate }) {
  return (
    <div style={{ background: P_T.bg, paddingBottom: 100 }}>
      <div style={{ padding: '18px' }}>
        <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.6, marginBottom: 4 }}>§ NEW ROUTE</div>
        <div style={{ fontFamily: P_T.fontD, fontSize: 28, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.5 }}>Plan</div>
      </div>

      <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {/* AI Builder — featured */}
        <button onClick={() => onNavigate('ai')} style={{
          background: P_T.cardElev, border: `1px solid ${P_T.border}`, borderLeft: `3px solid ${P_T.signal}`,
          padding: '18px 16px', cursor: 'pointer', textAlign: 'left',
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.signal, letterSpacing: 1.5, border: `1px solid ${P_T.signalDeep}`, padding: '2px 6px' }}>AI</span>
            <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.2 }}>RECOMMENDED</span>
          </div>
          <div style={{ fontFamily: P_T.fontD, fontSize: 18, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.2 }}>AI route builder</div>
          <div style={{ fontFamily: P_T.fontB, fontSize: 13, color: P_T.textMid, lineHeight: 1.5 }}>
            "Build me a 3-hour green-lane loop near the Peak District. Avoid deep mud, big-ADV friendly."
          </div>
          <div style={{ fontFamily: P_T.fontM, fontSize: 11, color: P_T.signalGlow, letterSpacing: 0.5, marginTop: 2 }}>OPEN BUILDER →</div>
        </button>

        {/* GPX Health Check */}
        <button onClick={() => onNavigate('gpx')} style={{
          background: P_T.card, border: `1px solid ${P_T.border}`,
          padding: '18px 16px', cursor: 'pointer', textAlign: 'left',
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <svg width="18" height="18" viewBox="0 0 20 20" fill="none" stroke={P_T.textHi} strokeWidth="1.4">
                <path d="M4 16 L4 4 L11 4 L16 9 L16 16 Z"/><path d="M11 4 L11 9 L16 9"/><path d="M7 11 L13 11 M7 13 L11 13"/>
              </svg>
              <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.5 }}>UPLOAD</span>
            </div>
          </div>
          <div style={{ fontFamily: P_T.fontD, fontSize: 18, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.2 }}>GPX health check</div>
          <div style={{ fontFamily: P_T.fontB, fontSize: 13, color: P_T.textMid, lineHeight: 1.5 }}>
            Upload any GPX — ROAMR checks for gaps, suspicious sections, private-land risk, surface mix, and stale data.
          </div>
        </button>

        {/* Draw on map */}
        <button style={{
          background: P_T.card, border: `1px solid ${P_T.border}`,
          padding: '18px 16px', cursor: 'pointer', textAlign: 'left',
          display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <svg width="18" height="18" viewBox="0 0 20 20" fill="none" stroke={P_T.textHi} strokeWidth="1.4">
              <path d="M3 17 L9 11 L13 15 L17 7"/><circle cx="9" cy="11" r="1.3" fill={P_T.textHi}/><circle cx="13" cy="15" r="1.3" fill={P_T.textHi}/><circle cx="17" cy="7" r="1.3" fill={P_T.signal}/>
            </svg>
            <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.5 }}>MANUAL</span>
          </div>
          <div style={{ fontFamily: P_T.fontD, fontSize: 18, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.2 }}>Draw on map</div>
          <div style={{ fontFamily: P_T.fontB, fontSize: 13, color: P_T.textMid, lineHeight: 1.5 }}>
            Tap to add waypoints. Snap to ways. Reverse, split, merge.
          </div>
        </button>
      </div>

      {/* Recent drafts */}
      <div style={{ marginTop: 24 }}>
        <P_SH kicker="§ DRAFTS · 2" title="Continue planning" />
        <div style={{ padding: '0 18px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { name: 'Weekend Snowdonia loop', state: 'AI · waiting for confirmation', when: '2h' },
            { name: 'Custom — drawn 14 May', state: '12 waypoints · 41 km drafted', when: '11d' },
          ].map((d, i) => (
            <div key={i} style={{ background: P_T.card, border: `1px solid ${P_T.border}`, padding: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontFamily: P_T.fontD, fontSize: 15, fontWeight: 500, color: P_T.textHi }}>{d.name}</div>
                <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 0.6, marginTop: 4 }}>{d.state.toUpperCase()}</div>
              </div>
              <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textLo, letterSpacing: 1 }}>{d.when.toUpperCase()}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// AI ROUTE BUILDER
// ────────────────────────────────────────────────────────────
function AiBuilderScreen({ onBack, onOpenRoute }) {
  const [step, setStep] = React.useState('prompt'); // prompt | thinking | result
  const [prompt, setPrompt] = React.useState('');
  const [plan, setPlan] = React.useState(null);
  const [error, setError] = React.useState('');
  const examples = [
    '3-hour green-lane loop in Peak District, big-ADV friendly, avoid mud',
    'Scenic gravel route under 40km with cafe stop',
    'Beginner hike near Snowdonia, 2-3 hours, dog-friendly',
    'Weekend in Wales with campsite and pub stop',
  ];

  const run = async (p) => {
    const nextPrompt = (p || examples[0]).trim();
    if (nextPrompt.length < 8) {
      setError('Describe the route you want in a little more detail.');
      return;
    }
    setPrompt(nextPrompt);
    setError('');
    setStep('thinking');
    try {
      const data = await window.ROAMR_API.routeBuilder(nextPrompt);
      setPlan(data.plan);
    } catch (err) {
      setPlan({
        title: 'Roych & Chapel Loop',
        summary: 'Demo fallback: the AI service did not respond, so ROAMR is showing the safe prototype route plan.',
        distanceKm: 38.4,
        elevationM: 612,
        duration: '2h 58m',
        difficulty: 'Intermediate',
        checks: ['AI unavailable', 'Use as planning draft only', 'Verify local signs and notices']
      });
      setError(err.message || 'AI route builder unavailable.');
    }
    setStep('result');
  };

  return (
    <div style={{ background: P_T.bg, height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P_T.border}`, display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: P_T.textHi, cursor: 'pointer', fontSize: 18 }}>←</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.signal, letterSpacing: 1.5 }}>AI ROUTE BUILDER</div>
          <div style={{ fontFamily: P_T.fontD, fontSize: 16, fontWeight: 600, color: P_T.textHi }}>Describe your ride</div>
        </div>
      </div>

      {step === 'prompt' && (
        <div style={{ flex: 1, padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 18, overflow: 'auto' }}>
          <div style={{ background: P_T.card, border: `1px solid ${P_T.border}`, padding: '14px' }}>
            <textarea value={prompt} onChange={e => setPrompt(e.target.value)} rows={4}
              placeholder="e.g. Build a 3-hour green-lane loop near the Peak District. Avoid deep mud. Big-ADV friendly. Pub stop ideal."
              style={{
                width: '100%', background: 'transparent', border: 'none', resize: 'none',
                color: P_T.textHi, fontFamily: P_T.fontB, fontSize: 15, lineHeight: 1.55, outline: 'none',
              }} />
            <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
              <P_Chip sm>3 hours</P_Chip>
              <P_Chip sm>Peak District</P_Chip>
              <P_Chip sm icon={<P_Act kind="moto" size={11}/>}><span style={{marginLeft:3}}>Big ADV</span></P_Chip>
              <P_Chip sm>Avoid mud</P_Chip>
              <P_Chip sm>+ Add</P_Chip>
            </div>
          </div>

          <div>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.5, marginBottom: 10 }}>§ EXAMPLES</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {examples.map(e => (
                <button key={e} onClick={() => run(e)} style={{
                  background: P_T.card, border: `1px solid ${P_T.border}`,
                  padding: '12px 14px', cursor: 'pointer', textAlign: 'left',
                  fontFamily: P_T.fontB, fontSize: 13, color: P_T.textMid, lineHeight: 1.4,
                }}>"{e}"</button>
              ))}
            </div>
          </div>

          <div style={{
            background: 'rgba(110,146,176,0.08)', border: `1px solid ${P_T.slate}`,
            padding: 12, fontFamily: P_T.fontB, fontSize: 12, color: P_T.textLo, lineHeight: 1.5,
          }}>
            <span style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.slate, letterSpacing: 1.5, marginRight: 6 }}>NOTE:</span>
            ROAMR's AI is a planning aid. It uses verified sources where available but routes should be checked on the ground before riding.
          </div>

          <button onClick={() => run(prompt || examples[0])} style={{
            background: P_T.signal, color: '#fff', border: 'none', padding: '14px',
            fontFamily: P_T.fontB, fontWeight: 500, fontSize: 14, cursor: 'pointer',
            marginTop: 'auto',
          }}>Generate route</button>
          {error && (
            <div style={{ fontFamily: P_T.fontB, fontSize: 12, color: P_T.amber, lineHeight: 1.4 }}>
              {error}
            </div>
          )}
        </div>
      )}

      {step === 'thinking' && (
        <div style={{ flex: 1, padding: '40px 18px', display: 'flex', flexDirection: 'column', gap: 18, alignItems: 'center', justifyContent: 'center' }}>
          <div style={{
            width: 50, height: 50, border: `2px solid ${P_T.border}`, borderTopColor: P_T.signal,
            borderRadius: '50%', animation: 'spin 0.9s linear infinite',
          }} />
          <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
          <div style={{ fontFamily: P_T.fontM, fontSize: 11, color: P_T.signalGlow, letterSpacing: 1.5 }}>BUILDING ROUTE…</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center' }}>
            {['Loading OSM byways in region', 'Filtering by big-ADV suitability', 'Checking TRO database (DCC)', 'Recent reports · 14 contributors', 'Optimising 3-hour loop'].map((l, i) => (
              <div key={i} style={{ fontFamily: P_T.fontM, fontSize: 11, color: i < 3 ? P_T.lichen : P_T.textMute, letterSpacing: 0.5 }}>
                {i < 3 ? '✓' : '·'} {l}
              </div>
            ))}
          </div>
        </div>
      )}

      {step === 'result' && (
        <div style={{ flex: 1, overflow: 'auto' }}>
          {/* User prompt echo */}
          <div style={{ padding: '14px 18px', background: P_T.card, borderBottom: `1px solid ${P_T.border}`, display: 'flex', gap: 10 }}>
            <span style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.textMute, letterSpacing: 1.5, marginTop: 2 }}>YOU</span>
            <div style={{ flex: 1, fontFamily: P_T.fontB, fontSize: 13, color: P_T.text, lineHeight: 1.5, fontStyle: 'italic' }}>"{prompt}"</div>
          </div>

          {/* Result map */}
          <div style={{ position: 'relative' }}>
            <P_Map height={220} dense showLabels
              routePath="M40 165 Q 80 140 110 110 Q 150 80 200 100 Q 260 130 310 95 Q 360 60 380 90 Q 360 130 320 150 Q 270 170 220 160 Q 170 150 120 170 Q 80 180 40 165"
              pins={[
                { x: 45, y: 165, label: 'R' },
                { x: 200, y: 100, color: '#0E110D', size: 5 },
                { x: 320, y: 150, color: '#0E110D', size: 5 },
                { x: 380, y: 90, color: P_T.signal, size: 6 },
              ]} />
          </div>

          {/* Stats */}
          <div style={{ padding: '20px 18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 14 }}>
              <div>
                <div style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.signal, letterSpacing: 1.5, marginBottom: 4 }}>§ ROAMR PROPOSAL · v1</div>
                <div style={{ fontFamily: P_T.fontD, fontSize: 20, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.3 }}>{plan?.title || 'Roych & Chapel Loop'}</div>
              </div>
              <P_Conf level="high" days={8} />
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
              <P_Stat value={String(plan?.distanceKm || '38.4')} unit="KM" size="l" />
              <P_Stat value={`+${plan?.elevationM || 612}`} unit="M GAIN" size="l" />
              <P_Stat value={plan?.duration || '2h 58m'} unit="EST" size="l" />
              <P_Stat value={(plan?.difficulty || 'Intermediate').slice(0,3).toUpperCase()} unit="DIFF" size="l" color={P_T.signalGlow} />
            </div>
          </div>

          {/* AI reasoning */}
          <div style={{ padding: '18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{
              background: P_T.card, border: `1px solid ${P_T.border}`, borderLeft: `3px solid ${P_T.signal}`,
              padding: 14, fontFamily: P_T.fontB, fontSize: 13, color: P_T.text, lineHeight: 1.55,
            }}>
              <span style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.signalGlow, letterSpacing: 1.5, marginRight: 6 }}>AI:</span>
              {plan?.summary || 'I picked 4 connected byways forming a loop from Hayfield. Surfaces are mostly dry per the last 8 days of reports — no deep mud sections. The Old Hall Inn at km 22 makes a natural pub stop. One small ford at km 11 (crossable, 12cm). All BOATs — no known TROs.'}
              {plan?.checks?.length ? (
                <ul style={{ margin: '10px 0 0', paddingLeft: 18 }}>
                  {plan.checks.slice(0, 4).map((check, i) => <li key={i}>{check}</li>)}
                </ul>
              ) : null}
              <div style={{ marginTop: 10, display: 'flex', gap: 8, fontFamily: P_T.fontM, fontSize: 9, color: P_T.textMute, letterSpacing: 1, flexWrap: 'wrap' }}>
                <span>3 SOURCES</span><span>·</span><span>12 REPORTS</span><span>·</span><span>DCC ROW · 2024</span>
              </div>
            </div>
          </div>

          {/* Surface */}
          <div style={{ padding: '18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 12 }}>§ SURFACE</div>
            <P_SB showLegend parts={[
              { label: 'Tarmac', pct: 24, color: '#5a6253' },
              { label: 'Byway', pct: 54, color: P_T.signal },
              { label: 'Rough', pct: 16, color: P_T.amber },
              { label: 'Tech', pct: 6, color: P_T.rust },
            ]}/>
          </div>

          {/* Make adjustments */}
          <div style={{ padding: '18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 12 }}>§ ADJUST</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['Make easier', 'Make harder', 'Avoid busy roads', 'Add cafe stop', 'Make scenic', 'Shorter', 'Longer', 'Regenerate'].map(a => (
                <P_Chip key={a} sm>+ {a}</P_Chip>
              ))}
            </div>
          </div>

          {/* CTA */}
          <div style={{ padding: '18px', display: 'flex', gap: 8 }}>
            <button onClick={() => onOpenRoute({
              ...window.ROUTES[0],
              name: plan?.title || 'Roych & Chapel Loop',
              distance: String(plan?.distanceKm || '38.4'),
              elev: `+${plan?.elevationM || 612}`,
              time: plan?.duration || '2h 58m',
              diff: plan?.difficulty || 'INTERMEDIATE',
              reports: 0,
              tags: ['AI draft', 'Verify access']
            })} style={{
              flex: 1, background: P_T.signal, color: '#fff', border: 'none', padding: '13px',
              fontFamily: P_T.fontB, fontWeight: 500, fontSize: 14, cursor: 'pointer',
            }}>Save route</button>
            <button onClick={() => setStep('prompt')} style={{
              background: P_T.card, color: P_T.textHi, border: `1px solid ${P_T.borderSoft}`, padding: '13px 14px',
              fontFamily: P_T.fontB, fontWeight: 500, fontSize: 14, cursor: 'pointer',
            }}>Try again</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// GPX HEALTH CHECK
// ────────────────────────────────────────────────────────────
function GpxCheckScreen({ onBack }) {
  const [step, setStep] = React.useState('upload'); // upload | analysing | result
  const [filename, setFilename] = React.useState('');
  const [health, setHealth] = React.useState(null);
  const [error, setError] = React.useState('');
  const fileRef = React.useRef(null);

  const start = async (name) => {
    setFilename(name);
    setError('');
    setStep('analysing');
    try {
      const data = await window.ROAMR_API.gpxHealth(name);
      setHealth(data);
    } catch (err) {
      setError(err.message || 'GPX health check unavailable.');
      setHealth(null);
    }
    setStep('result');
  };

  return (
    <div style={{ background: P_T.bg, minHeight: '100%' }}>
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P_T.border}`, display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: P_T.textHi, cursor: 'pointer', fontSize: 18 }}>←</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P_T.fontM, fontSize: 9, color: P_T.signal, letterSpacing: 1.5 }}>AI</div>
          <div style={{ fontFamily: P_T.fontD, fontSize: 16, fontWeight: 600, color: P_T.textHi }}>GPX health check</div>
        </div>
      </div>

      {step === 'upload' && (
        <div style={{ padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 18 }}>
          <input ref={fileRef} type="file" accept=".gpx,application/gpx+xml,text/xml,application/xml" style={{ display: 'none' }}
            onChange={event => {
              const file = event.target.files?.[0];
              if (file) start(file.name);
              event.target.value = '';
            }} />
          <button onClick={() => fileRef.current?.click()} style={{
            background: P_T.card, border: `2px dashed ${P_T.borderSoft}`, padding: '40px 20px',
            cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
          }}>
            <svg width="44" height="44" viewBox="0 0 44 44" fill="none" stroke={P_T.signal} strokeWidth="1.5">
              <path d="M22 8 L22 28 M14 18 L22 8 L30 18"/>
              <path d="M8 30 L8 36 L36 36 L36 30"/>
            </svg>
            <div style={{ fontFamily: P_T.fontD, fontSize: 17, fontWeight: 600, color: P_T.textHi }}>Upload .gpx file</div>
            <div style={{ fontFamily: P_T.fontB, fontSize: 13, color: P_T.textLo, textAlign: 'center', maxWidth: 240 }}>
              Tap to choose a real file. ROAMR will run the current server-side health endpoint and show a safe draft result.
            </div>
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: P_T.textMute, fontFamily: P_T.fontM, fontSize: 10, letterSpacing: 1.5 }}>
            <span style={{ flex: 1, height: 1, background: P_T.border }} /> OR <span style={{ flex: 1, height: 1, background: P_T.border }} />
          </div>

          <button style={{ background: P_T.card, border: `1px solid ${P_T.border}`, padding: '14px', cursor: 'pointer',
            fontFamily: P_T.fontB, fontSize: 14, color: P_T.text, textAlign: 'left' }}>
            Paste GPX URL or share link
          </button>

          <div>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1.5, marginBottom: 10 }}>§ RECENT</div>
            {['peak-loop-2024.gpx', 'snowdonia-day1.gpx'].map(n => (
              <button key={n} onClick={() => start(n)} style={{
                width: '100%', background: P_T.card, border: `1px solid ${P_T.border}`, marginBottom: 6,
                padding: '12px 14px', textAlign: 'left', cursor: 'pointer',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span style={{ fontFamily: P_T.fontM, fontSize: 12, color: P_T.text }}>{n}</span>
                <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute }}>›</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {step === 'analysing' && (
        <div style={{ padding: '40px 18px', display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center' }}>
          <div style={{ width: 50, height: 50, border: `2px solid ${P_T.border}`, borderTopColor: P_T.signal,
            borderRadius: '50%', animation: 'spin 0.9s linear infinite' }} />
          <div style={{ fontFamily: P_T.fontM, fontSize: 11, color: P_T.signalGlow, letterSpacing: 1.5 }}>ANALYSING {filename.toUpperCase()}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {['Parsing 1,247 trackpoints', 'Detecting GPS gaps', 'Matching against ROW database', 'Checking TRO records', 'Surface estimation from OSM tags', 'Cross-referencing recent reports'].map((l, i) => (
              <div key={i} style={{ fontFamily: P_T.fontM, fontSize: 11, color: i < 4 ? P_T.lichen : P_T.textMute, letterSpacing: 0.5 }}>{i < 4 ? '✓' : '·'} {l}</div>
            ))}
          </div>
        </div>
      )}

      {step === 'result' && (
        <div>
          {/* File header */}
          <div style={{ padding: '14px 18px', background: P_T.card, borderBottom: `1px solid ${P_T.border}`, display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 1 }}>FILE</span>
            <span style={{ fontFamily: P_T.fontM, fontSize: 12, color: P_T.textHi, flex: 1 }}>{filename}</span>
            <span style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute }}>89 KB</span>
          </div>

          {/* Health score */}
          <div style={{ padding: '24px 18px', borderBottom: `1px solid ${P_T.border}`, display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{
              width: 84, height: 84, position: 'relative',
              border: `2px solid ${P_T.border}`, borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column',
            }}>
              <svg width="88" height="88" viewBox="0 0 88 88" style={{ position: 'absolute', top: -2, left: -2, transform: 'rotate(-90deg)' }}>
                <circle cx="44" cy="44" r="42" stroke={P_T.amber} strokeWidth="2.5" fill="none"
                  strokeDasharray={`${0.74 * 264} 264`} />
              </svg>
              <span style={{ fontFamily: P_T.fontM, fontSize: 24, fontWeight: 600, color: P_T.amber }}>{health?.score || 74}</span>
              <span style={{ fontFamily: P_T.fontM, fontSize: 8, color: P_T.textMute, letterSpacing: 1 }}>/100</span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 4 }}>§ HEALTH SCORE</div>
              <div style={{ fontFamily: P_T.fontD, fontSize: 18, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.2 }}>{health?.verdict || 'Mostly ready, with caveats'}</div>
              <div style={{ fontFamily: P_T.fontB, fontSize: 12, color: P_T.textLo, marginTop: 4, lineHeight: 1.5 }}>{error || '3 warnings · 1 critical to review before riding'}</div>
            </div>
          </div>

          {/* Detected stats */}
          <div style={{ padding: '20px 18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 14 }}>§ DETECTED</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 16 }}>
              <P_Stat value={String(health?.stats?.distanceKm || '38.4')} unit="KILOMETRES" size="m" />
              <P_Stat value={`+${health?.stats?.elevationM || 612}`} unit="M ELEVATION" size="m" />
              <P_Stat value={health?.stats?.movingTime || '3h 04m'} unit="EST. MOVING" size="m" />
              <P_Stat value={(health?.stats?.difficulty || 'Intermediate').slice(0,3).toUpperCase()} unit="DIFFICULTY" size="m" color={P_T.signalGlow} />
            </div>
            <div style={{ marginTop: 16 }}>
              <P_SB showLegend parts={[
                { label: 'Tarmac', pct: 18, color: '#5a6253' },
                { label: 'Byway', pct: 54, color: P_T.signal },
                { label: 'Rough', pct: 22, color: P_T.amber },
                { label: 'Tech', pct: 6, color: P_T.rust },
              ]}/>
            </div>
          </div>

          {/* Findings */}
          <div style={{ padding: '20px 18px', borderBottom: `1px solid ${P_T.border}` }}>
            <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 14 }}>§ FINDINGS</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {(health?.findings || [
                { sev: 'CRITICAL', sevC: P_T.rust, title: '1.2 km section crosses possible private land', body: 'Track near km 14 leaves the BOAT and crosses what OSM flags as fenced agricultural land. No public right-of-way found. Consider re-routing.' },
                { sev: 'WARN', sevC: P_T.amber, title: 'GPS gap of 340m near km 22', body: 'Possible tunnel, tree cover or recording pause. Manually verify continuity.' },
                { sev: 'WARN', sevC: P_T.amber, title: 'Source data older than 18 months', body: 'GPX was last edited 2024-09. TRF and council records have updates since then — re-verify access.' },
                { sev: 'INFO', sevC: P_T.slate, title: '1 small ford detected at km 11', body: 'Crossable per recent reports. 12cm typical depth.' },
                { sev: 'OK', sevC: P_T.lichen, title: 'No known active TRO matches', body: 'Cross-referenced against DCC and Peak District NPA databases (8 days fresh).' },
              ]).map((f, i) => {
                const sev = (f.sev || f.severity || 'info').toUpperCase();
                const sevC = f.sevC || (sev === 'CRITICAL' ? P_T.rust : sev === 'WARNING' || sev === 'WARN' ? P_T.amber : sev === 'OK' ? P_T.lichen : P_T.slate);
                return (
                  <div key={i} style={{ background: P_T.card, border: `1px solid ${P_T.border}`, padding: 14 }}>
                    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                      <span style={{ fontFamily: P_T.fontM, fontSize: 9, color: sevC, border: `1px solid ${sevC}`, padding: '2px 6px', letterSpacing: 1, whiteSpace: 'nowrap', marginTop: 1 }}>{sev}</span>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: P_T.fontB, fontSize: 13, fontWeight: 600, color: P_T.textHi, marginBottom: 4 }}>{f.title}</div>
                        <div style={{ fontFamily: P_T.fontB, fontSize: 12, color: P_T.textLo, lineHeight: 1.5 }}>{f.body}</div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Actions */}
          <div style={{ padding: '18px', display: 'flex', gap: 8 }}>
            <button style={{ flex: 1, background: P_T.signal, color: '#fff', border: 'none', padding: '13px', fontFamily: P_T.fontB, fontWeight: 500, fontSize: 14, cursor: 'pointer' }}>Save as private route</button>
            <button style={{ background: P_T.card, color: P_T.textHi, border: `1px solid ${P_T.borderSoft}`, padding: '13px 14px', fontFamily: P_T.fontM, fontSize: 11, letterSpacing: 1, cursor: 'pointer' }}>FIX</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// NAVIGATION MODE (Adv moto, big-button)
// ────────────────────────────────────────────────────────────
function NavScreen({ route, onExit }) {
  return (
    <div style={{ background: '#000', height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Top: next turn */}
      <div style={{ background: P_T.signal, padding: '20px 18px 18px', display: 'flex', alignItems: 'center', gap: 18 }}>
        <svg width="48" height="48" viewBox="0 0 48 48" fill="none" stroke="#fff" strokeWidth="3">
          <path d="M10 32 L10 18 L28 18 L28 8 L40 22 L28 36 L28 26 L18 26 L18 32 Z" strokeLinejoin="round"/>
        </svg>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: P_T.fontM, fontSize: 48, fontWeight: 600, color: '#fff', lineHeight: 1, letterSpacing: -1 }}>180<span style={{ fontSize: 22, opacity: 0.7 }}>m</span></div>
          <div style={{ fontFamily: P_T.fontB, fontSize: 16, color: '#fff', fontWeight: 500, marginTop: 4 }}>Right onto Roych Clough</div>
        </div>
      </div>

      {/* Big map */}
      <div style={{ flex: 1, position: 'relative' }}>
        <svg viewBox="0 0 400 500" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%', display: 'block' }}>
          <defs>
            <pattern id="grid-nav" width="50" height="50" patternUnits="userSpaceOnUse">
              <path d="M50 0 L0 0 L0 50" fill="none" stroke="#0e110d" strokeWidth="1"/>
            </pattern>
          </defs>
          <rect width="400" height="500" fill="#06080a"/>
          <rect width="400" height="500" fill="url(#grid-nav)" />
          <g stroke="#1c211a" strokeWidth="1" fill="none">
            <path d="M0 100 Q 100 80 200 90 T 400 110" />
            <path d="M0 160 Q 100 140 200 150 T 400 170" />
            <path d="M0 220 Q 100 200 200 210 T 400 230" />
            <path d="M0 280 Q 100 260 200 270 T 400 290" />
            <path d="M0 340 Q 100 320 200 330 T 400 350" />
          </g>
          {/* upcoming path bright */}
          <path d="M200 380 L 200 320 Q 210 270 250 260 L 320 240" stroke="#E25E1F" strokeWidth="6" fill="none" strokeLinecap="round"/>
          {/* past path faded */}
          <path d="M200 380 L 200 460" stroke="#E25E1F" strokeWidth="4" fill="none" opacity="0.4"/>
          {/* user position */}
          <g transform="translate(200,380)">
            <circle r="22" fill="#E25E1F" opacity="0.15"/>
            <circle r="10" fill="#E25E1F" stroke="#fff" strokeWidth="3"/>
            <path d="M0 -16 L-7 -4 L7 -4 Z" fill="#fff"/>
          </g>
          {/* upcoming waypoint */}
          <g transform="translate(320,240)">
            <circle r="10" fill="#0E110D" stroke="#F2EDE2" strokeWidth="2"/>
            <circle r="3" fill="#F2EDE2"/>
          </g>
          {/* compass */}
          <g transform="translate(360,40)">
            <circle r="20" fill="rgba(14,17,13,0.8)" stroke="#3A4036" strokeWidth="1"/>
            <text y="-6" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="10" fontWeight="700" fill="#E25E1F">N</text>
            <path d="M0 -14 L0 -8" stroke="#E25E1F" strokeWidth="2"/>
          </g>
        </svg>

        {/* Hazard alert overlay */}
        <div style={{
          position: 'absolute', top: 14, left: 14,
          background: P_T.amber, color: '#0E110D',
          padding: '8px 10px', fontFamily: P_T.fontM, fontSize: 11, fontWeight: 600, letterSpacing: 0.5,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <span>⚠</span> FORD IN 1.2 KM
        </div>
      </div>

      {/* Bottom: big stats + actions */}
      <div style={{ background: P_T.bg, borderTop: `1px solid ${P_T.border}`, padding: '18px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 16 }}>
          <P_Stat value="12.4" unit="KM LEFT" size="xl" />
          <P_Stat value="42:18" unit="ETA" size="xl" />
          <P_Stat value="48" unit="KM/H" size="xl" color={P_T.signal} />
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onExit} style={{
            flex: 1, background: P_T.rust, color: '#fff', border: 'none', padding: '16px',
            fontFamily: P_T.fontB, fontWeight: 600, fontSize: 14, cursor: 'pointer', letterSpacing: 0.5,
          }}>End ride</button>
          <button style={{
            background: P_T.card, color: P_T.textHi, border: `1px solid ${P_T.borderSoft}`, padding: '16px 18px',
            fontFamily: P_T.fontM, fontSize: 11, cursor: 'pointer', letterSpacing: 1.2,
          }}>⚠ REPORT</button>
          <button style={{
            background: P_T.card, color: P_T.textHi, border: `1px solid ${P_T.borderSoft}`, padding: '16px 18px',
            fontFamily: P_T.fontM, fontSize: 11, cursor: 'pointer', letterSpacing: 1.2,
          }}>⏸</button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// PRICING / UPGRADE
// ────────────────────────────────────────────────────────────
function UpgradeScreen({ onBack }) {
  const [plan, setPlan] = React.useState('annual');
  const plans = {
    monthly: { price: '£4.99', cadence: '/MONTH', sub: 'Billed monthly', save: null },
    annual:  { price: '£39.99', cadence: '/YEAR', sub: 'Equivalent to £3.33/mo', save: '33% LAUNCH OFFER' },
    founder: { price: '£99', cadence: 'ONCE', sub: 'Lifetime access · Founder badge', save: 'LIMITED · 412 LEFT' },
  };
  const p = plans[plan];

  const features = [
    ['Offline route packs',          'All',     'Limited'],
    ['GPX import / export',          true,      'Import only'],
    ['AI route builder',             'Unlimited', '3 / month'],
    ['TRO + closure alerts',         true,      false],
    ['Unlimited saved routes',       true,      '20'],
    ['Access confidence history',    true,      'Current only'],
    ['Route comparison',             true,      false],
    ['Weather overlays',             true,      false],
    ['Club / private sharing',       true,      false],
    ['Full turn-by-turn navigation', true,      'Basic'],
  ];

  return (
    <div style={{ background: P_T.bg, minHeight: '100%', paddingBottom: 80 }}>
      <div style={{ padding: '14px 18px', borderBottom: `1px solid ${P_T.border}`, display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: P_T.textHi, cursor: 'pointer', fontSize: 18 }}>←</button>
        <div style={{ flex: 1, fontFamily: P_T.fontD, fontSize: 16, fontWeight: 600, color: P_T.textHi }}>Upgrade</div>
      </div>

      {/* Hero */}
      <div style={{ padding: '32px 18px 24px', textAlign: 'left' }}>
        <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 2, marginBottom: 8 }}>§ ROAMR PREMIUM</div>
        <div style={{ fontFamily: P_T.fontD, fontSize: 32, fontWeight: 600, color: P_T.textHi, letterSpacing: -0.6, lineHeight: 1.1 }}>The whole map.<br/>The whole adventure.</div>
        <p style={{ fontFamily: P_T.fontB, fontSize: 14, color: P_T.textLo, lineHeight: 1.55, marginTop: 12 }}>
          Offline packs, TRO alerts, AI route builder, unlimited saves, weather overlays, club sharing.
        </p>
      </div>

      {/* Plan toggle */}
      <div style={{ padding: '0 18px', display: 'flex', gap: 6, marginBottom: 18 }}>
        {Object.keys(plans).map(k => (
          <button key={k} onClick={() => setPlan(k)} style={{
            flex: 1, padding: '10px 4px',
            background: plan === k ? P_T.textHi : 'transparent',
            color: plan === k ? P_T.bg : P_T.textMid,
            border: `1px solid ${plan === k ? P_T.textHi : P_T.borderSoft}`,
            fontFamily: P_T.fontM, fontSize: 11, letterSpacing: 1, cursor: 'pointer',
            textTransform: 'uppercase',
          }}>{k}</button>
        ))}
      </div>

      {/* Selected plan card */}
      <div style={{ padding: '0 18px 24px' }}>
        <div style={{ background: P_T.cardElev, border: `1px solid ${P_T.signalDeep}`, borderLeft: `3px solid ${P_T.signal}`, padding: '20px 18px' }}>
          {p.save && (
            <div style={{ display: 'inline-flex', fontFamily: P_T.fontM, fontSize: 9, color: P_T.signal, letterSpacing: 1.5, border: `1px solid ${P_T.signalDeep}`, padding: '3px 7px', marginBottom: 14 }}>{p.save}</div>
          )}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <span style={{ fontFamily: P_T.fontD, fontSize: 44, fontWeight: 600, color: P_T.textHi, letterSpacing: -1, lineHeight: 1 }}>{p.price}</span>
            <span style={{ fontFamily: P_T.fontM, fontSize: 11, color: P_T.textLo, letterSpacing: 1.5 }}>{p.cadence}</span>
          </div>
          <div style={{ fontFamily: P_T.fontB, fontSize: 12, color: P_T.textLo, marginTop: 4 }}>{p.sub}</div>
          <button style={{
            width: '100%', background: P_T.signal, color: '#fff', border: 'none', padding: '14px',
            fontFamily: P_T.fontB, fontWeight: 500, fontSize: 14, cursor: 'pointer', marginTop: 20,
          }}>Start 14-day trial</button>
          <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.textMute, letterSpacing: 0.6, marginTop: 10, textAlign: 'center' }}>Cancel anytime. No charge during trial.</div>
        </div>
      </div>

      {/* Comparison */}
      <div style={{ padding: '0 18px' }}>
        <div style={{ fontFamily: P_T.fontM, fontSize: 10, color: P_T.signal, letterSpacing: 1.5, marginBottom: 14 }}>§ COMPARE</div>
        <div style={{ background: P_T.card, border: `1px solid ${P_T.border}` }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1.7fr 0.8fr 0.8fr', padding: '12px 14px', borderBottom: `1px solid ${P_T.border}`, fontFamily: P_T.fontM, fontSize: 9, color: P_T.textMute, letterSpacing: 1.2 }}>
            <span>FEATURE</span><span style={{ textAlign: 'center', color: P_T.signal }}>PREMIUM</span><span style={{ textAlign: 'center' }}>FREE</span>
          </div>
          {features.map(([name, prem, free], i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '1.7fr 0.8fr 0.8fr', padding: '11px 14px',
              borderTop: i > 0 ? `1px solid ${P_T.border}` : 'none', alignItems: 'center',
            }}>
              <span style={{ fontFamily: P_T.fontB, fontSize: 13, color: P_T.text }}>{name}</span>
              <span style={{ textAlign: 'center', fontFamily: P_T.fontM, fontSize: 11 }}>
                {prem === true ? <span style={{ color: P_T.lichen }}>✓</span> : <span style={{ color: P_T.textHi }}>{prem}</span>}
              </span>
              <span style={{ textAlign: 'center', fontFamily: P_T.fontM, fontSize: 11 }}>
                {free === true ? <span style={{ color: P_T.lichen }}>✓</span> :
                 free === false ? <span style={{ color: P_T.textMute }}>—</span> :
                 <span style={{ color: P_T.textLo, fontSize: 10 }}>{free}</span>}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Trust block */}
      <div style={{ padding: '24px 18px', fontFamily: P_T.fontB, fontSize: 11, color: P_T.textLo, lineHeight: 1.6 }}>
        <strong style={{ color: P_T.textHi }}>Cancel anytime.</strong> Restore previous purchases on this device.
        Family plan and Club plans available for 4+ riders.
      </div>
    </div>
  );
}

Object.assign(window, { PlanScreen, AiBuilderScreen, GpxCheckScreen, NavScreen, UpgradeScreen });
