// screens-create.jsx — Create run flow (single-screen structured form, scrollable)

// Lazy-load Leaflet CSS + JS once
let leafletReady = false;
function ensureLeaflet(cb) {
  if (typeof L !== 'undefined') { cb(); return; }
  if (leafletReady) { const t = setInterval(() => { if (typeof L !== 'undefined') { clearInterval(t); cb(); } }, 50); return; }
  leafletReady = true;
  const css = document.createElement('link');
  css.rel = 'stylesheet'; css.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
  document.head.appendChild(css);
  const js = document.createElement('script');
  js.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
  js.onload = cb;
  document.head.appendChild(js);
}

function MapPicker({ initial, onConfirm, onClose }) {
  const mapRef = React.useRef(null);
  const leafletMap = React.useRef(null);
  const [query, setQuery] = React.useState('');
  const [searching, setSearching] = React.useState(false);
  const [label, setLabel] = React.useState(initial || '');
  const [coords, setCoords] = React.useState(null);

  React.useEffect(() => {
    ensureLeaflet(() => {
      if (!mapRef.current || leafletMap.current) return;
      const startLatLng = [51.462, -0.139]; // Clapham Common default
      const map = L.map(mapRef.current, { zoomControl: false }).setView(startLatLng, 15);
      L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
        attribution: '© OpenStreetMap © CARTO', maxZoom: 19,
      }).addTo(map);
      L.control.zoom({ position: 'bottomright' }).addTo(map);
      leafletMap.current = map;
      setCoords(startLatLng);
      map.on('moveend', () => {
        const c = map.getCenter();
        setCoords([c.lat, c.lng]);
      });
    });
    return () => { if (leafletMap.current) { leafletMap.current.remove(); leafletMap.current = null; } };
  }, []);

  const search = async () => {
    if (!query.trim()) return;
    setSearching(true);
    try {
      const res = await fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=1`);
      const data = await res.json();
      if (data[0] && leafletMap.current) {
        const lat = parseFloat(data[0].lat), lng = parseFloat(data[0].lon);
        leafletMap.current.setView([lat, lng], 16);
        setLabel(data[0].name || data[0].display_name.split(',')[0].trim());
      }
    } catch(e) {}
    setSearching(false);
  };

  const confirm = () => {
    const map = leafletMap.current;
    if (!map) return;
    const c = map.getCenter();
    const name = label || query || `${c.lat.toFixed(4)}°N, ${Math.abs(c.lng).toFixed(4)}°W`;
    onConfirm(name, [c.lat, c.lng]);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 30, display: 'flex', flexDirection: 'column', background: PACER.bg }}>
      {/* Header */}
      <div style={{ padding: '14px 16px 10px', display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 10, border: `1px solid ${PACER.border}`,
          background: 'transparent', color: PACER.text, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="close" size={18} color={PACER.text}/>
        </button>
        <div style={{ flex: 1, position: 'relative' }}>
          <input
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && search()}
            placeholder="Search location…"
            style={{
              width: '100%', boxSizing: 'border-box', height: 40,
              background: PACER.inset, border: `1px solid ${PACER.border}`,
              borderRadius: 10, padding: '0 40px 0 14px',
              color: PACER.text, fontFamily: PACER.font, fontSize: 14,
              outline: 'none',
            }}
          />
          <button onClick={search} style={{
            position: 'absolute', right: 6, top: '50%', transform: 'translateY(-50%)',
            background: 'transparent', border: 'none', cursor: 'pointer', padding: 4,
          }}>
            {searching
              ? <div style={{ width: 16, height: 16, border: `2px solid ${PACER.lime}`, borderTopColor: 'transparent', borderRadius: '50%', animation: 'spin 0.6s linear infinite' }}/>
              : <Icon name="search" size={16} color={PACER.lime}/>
            }
          </button>
        </div>
      </div>

      {/* Map */}
      <div style={{ flex: 1, position: 'relative' }}>
        <div ref={mapRef} style={{ width: '100%', height: '100%' }}/>
        {/* Fixed center pin */}
        <div style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: 'translate(-50%, -100%)',
          pointerEvents: 'none', zIndex: 999,
        }}>
          <div style={{ width: 28, height: 28, background: PACER.lime, borderRadius: '50% 50% 50% 0', transform: 'rotate(-45deg)', boxShadow: '0 2px 8px rgba(0,0,0,0.4)', border: '2px solid #0a0c0a' }}/>
        </div>
        {/* Pin shadow */}
        <div style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: 'translate(-50%, 4px)',
          width: 10, height: 4, background: 'rgba(0,0,0,0.3)', borderRadius: '50%',
          pointerEvents: 'none', zIndex: 999,
        }}/>
        {/* Instruction */}
        <div style={{
          position: 'absolute', bottom: 16, left: '50%', transform: 'translateX(-50%)',
          background: 'rgba(10,12,10,0.85)', backdropFilter: 'blur(8px)',
          border: `1px solid ${PACER.border}`, borderRadius: 99,
          padding: '7px 14px', whiteSpace: 'nowrap',
          fontFamily: PACER.font, fontSize: 12.5, color: PACER.textDim,
          pointerEvents: 'none', zIndex: 999,
        }}>
          Drag to where the run starts
        </div>
      </div>

      {/* Confirm bar */}
      <div style={{ padding: '12px 16px', flexShrink: 0, background: PACER.bg, borderTop: `1px solid ${PACER.border}` }}>
        {label ? (
          <div style={{ fontFamily: PACER.font, fontSize: 13, color: PACER.textDim, marginBottom: 6, textAlign: 'center' }}>
            📍 {label}
          </div>
        ) : null}
        <div style={{ fontFamily: PACER.font, fontSize: 11.5, color: PACER.textMute, textAlign: 'center', marginBottom: 10, lineHeight: 1.4 }}>
          Approximate area shown until you approve runners
        </div>
        <button onClick={confirm} style={{
          width: '100%', height: 50, borderRadius: 14, border: 'none',
          background: PACER.lime, color: PACER.limeInk,
          fontFamily: PACER.font, fontSize: 16, fontWeight: 600, cursor: 'pointer',
        }}>
          Set this location
        </button>
      </div>

      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

function FormSection({ label, children, hint }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10,
      }}>
        <div style={{
          fontFamily: PACER.font, fontSize: 11, fontWeight: 600,
          color: PACER.textMute, textTransform: 'uppercase', letterSpacing: 1.4,
        }}>{label}</div>
        {hint && <span style={{ fontFamily: PACER.font, fontSize: 11, color: PACER.textSubtle }}>{hint}</span>}
      </div>
      {children}
    </div>
  );
}

function SegmentedControl({ options, value, onChange, mono }) {
  return (
    <div style={{
      display: 'flex', background: PACER.inset, border: `1px solid ${PACER.border}`,
      borderRadius: 12, padding: 4, gap: 4,
    }}>
      {options.map(o => {
        const v = typeof o === 'string' ? o : o.value;
        const label = typeof o === 'string' ? o : o.label;
        return (
          <button key={v} onClick={() => onChange(v)} style={{
            flex: 1, height: 38, borderRadius: 9, border: 'none',
            background: value === v ? PACER.card : 'transparent',
            color: value === v ? PACER.text : PACER.textMute,
            fontFamily: mono ? PACER.mono : PACER.font, fontSize: 13.5,
            fontWeight: value === v ? 600 : 500, cursor: 'pointer',
            transition: 'all .15s', letterSpacing: mono ? 0 : -0.1,
          }}>{label}</button>
        );
      })}
    </div>
  );
}

function PaceRangeSlider({ min = '6:00' }) {
  const ticks = ['8:00','7:30','7:00','6:30','6:00','5:30','5:00','4:30'];
  const N = ticks.length - 1;
  const initIdx = ticks.indexOf(min);
  const [idx, setIdx] = React.useState(initIdx >= 0 ? initIdx : 4);
  const pct = (idx / N) * 100;
  const toMins = (t) => parseInt(t) * 60 + parseInt(t.split(':')[1]);
  const est = (t) => Math.round(toMins(t) * 5 / 60);
  return (
    <div style={{ background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14, padding: '18px 18px 14px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontFamily: PACER.mono, fontSize: 22, fontWeight: 500, color: PACER.text, letterSpacing: -0.5 }}>
            {ticks[idx]}<span style={{ color: PACER.textMute, fontSize: 14 }}>/km</span>
          </div>
          <div style={{ fontFamily: PACER.font, fontSize: 11.5, color: PACER.textMute, marginTop: 2 }}>
            5K in ~{est(ticks[idx])} min
          </div>
        </div>
        <span style={{ fontFamily: PACER.font, fontSize: 10.5, fontWeight: 600, color: PACER.lime, textTransform: 'uppercase', letterSpacing: 1.2 }}>Matches you</span>
      </div>
      <div style={{ position: 'relative', height: 32 }}>
        <div style={{ position: 'absolute', top: 14, left: 0, right: 0, height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 99 }}/>
        <div style={{ position: 'absolute', top: 14, left: 0, width: `${pct}%`, height: 4, background: PACER.lime, borderRadius: 99 }}/>
        <div style={{ position: 'absolute', top: 8, left: `${pct}%`, transform: 'translateX(-50%)', width: 16, height: 16, borderRadius: '50%', background: PACER.lime, border: `3px solid ${PACER.bg}`, boxShadow: `0 0 0 1px ${PACER.lime}`, pointerEvents: 'none' }}/>
        <input type="range" min="0" max={N} value={idx} onChange={e => setIdx(parseInt(e.target.value))}
          style={{ position: 'absolute', inset: 0, width: '100%', height: 32, opacity: 0, cursor: 'pointer', appearance: 'none' }}/>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: PACER.mono, fontSize: 9.5, color: PACER.textSubtle, marginTop: 2 }}>
        {ticks.filter((_, i) => i % 2 === 0).map(t => <span key={t}>{t}</span>)}
      </div>
    </div>
  );
}

function CreateScreen({ nav, onPublish, initialStep = 0, initialRun = null, editMode = false }) {
  const knownDist = ['3K', '5K', '10K'];
  const initDist = initialRun ? (knownDist.includes(initialRun.distance) ? initialRun.distance : 'Custom') : '5K';
  const initCustomDist = initialRun && !knownDist.includes(initialRun.distance) ? initialRun.distance.replace('K', '') : '';
  const [title, setTitle] = React.useState(initialRun ? initialRun.title : 'Easy Friday shakeout');
  const [area, setArea] = React.useState(initialRun ? initialRun.area : 'Clapham Common');
  const [showMapPicker, setShowMapPicker] = React.useState(false);
  const [distance, setDistance] = React.useState(initDist);
  const [customDistance, setCustomDistance] = React.useState(initCustomDist);
  const [hostNote, setHostNote] = React.useState(initialRun ? (initialRun.notes || '') : '');
  const HOST_NOTE_MAX_WORDS = 20;
  const hostNoteWords = hostNote.trim() === '' ? 0 : hostNote.trim().split(/\s+/).length;
  const hostNoteOver = hostNoteWords > HOST_NOTE_MAX_WORDS;
  const customDistNum = parseInt(customDistance, 10);
  const customDistError = customDistance !== '' && (!/^\d+$/.test(customDistance) || customDistNum < 1 || customDistNum > 50);
  const [level, setLevel] = React.useState('Beginner');
  const [date, setDate] = React.useState(initialRun ? initialRun.when : 'Fri 22');
  const [time, setTime] = React.useState(initialRun ? initialRun.time : '18:30');
  const [groupSize, setGroupSize] = React.useState(initialRun ? initialRun.capacity : 6);
  const [visibility, setVisibility] = React.useState('public');
  const [hostApproval, setHostApproval] = React.useState(true);
  const [step, setStep] = React.useState(initialStep); // 0 = form, 1 = preview, 2 = published

  // --- Published toast state ---
  if (step === 2) {
    return (
      <div style={{
        background: PACER.bg, minHeight: '100%', color: PACER.text, fontFamily: PACER.font,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: '0 30px', position: 'relative',
      }}>
        <div style={{
          width: 80, height: 80, borderRadius: '50%', background: PACER.lime,
          display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24,
          boxShadow: `0 0 0 12px ${PACER.limeSoft}`,
        }}>
          <Icon name="check" size={40} color={PACER.limeInk}/>
        </div>
        <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: -0.7, marginBottom: 8, textAlign: 'center' }}>
          {editMode ? 'Run updated' : 'Run published'}
        </div>
        <div style={{ fontSize: 14, color: PACER.textDim, textAlign: 'center', marginBottom: 28, lineHeight: 1.5 }}>
          {editMode
            ? 'Changes saved. Participants have been notified.'
            : <span>Folks in {area.split(' ')[0]} at your pace will see it now.<br/>We'll ping you when someone requests.</span>
          }
        </div>
        <div style={{ display: 'flex', gap: 10, width: '100%', maxWidth: 280 }}>
          <Btn variant="primary" size="lg" style={{ flex: 1 }} onClick={() => { onPublish(); nav('home'); }}>
            Back to runs
          </Btn>
        </div>
      </div>
    );
  }

  // --- Preview step ---
  if (step === 1) {
    return (
      <div style={{ background: PACER.bg, height: '100%', color: PACER.text, fontFamily: PACER.font, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{
          flexShrink: 0, padding: `${SCREEN_TOP}px 16px 12px`, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button onClick={() => setStep(0)} style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'rgba(255,255,255,0.04)', border: `1px solid ${PACER.border}`,
            color: PACER.text, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="chevL" size={20} color={PACER.text}/>
          </button>
          <div style={{ fontSize: 16, fontWeight: 600 }}>Preview</div>
          <div style={{ width: 40 }}/>
        </div>
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 20px 0' }}>
          <div style={{ fontFamily: PACER.font, fontSize: 12.5, color: PACER.textDim, marginBottom: 16, lineHeight: 1.5 }}>
            This is how runners will see your run in the feed.
          </div>
          <div style={{ marginBottom: 24 }}>
            <RunCard run={{
              id: 'preview', title, area, distance,
              paceMin: '6:00', paceMax: '6:45',
              level: '',
              capacity: groupSize, joined: ['anna'],
              when: date.split(' ')[0], time,
              host: 'anna', womenOnly: visibility === 'women-only',
            }} onClick={() => {}}/>
          </div>
          <div style={{
            background: PACER.inset, border: `1px solid ${PACER.border}`,
            borderRadius: 14, padding: 14,
          }}>
            <div style={{
              fontFamily: PACER.font, fontSize: 11, fontWeight: 600,
              color: PACER.textMute, textTransform: 'uppercase', letterSpacing: 1.4, marginBottom: 8,
            }}>Safety defaults</div>
            <div style={{ display: 'grid', gap: 8 }}>
              {[
                ['Host approval required', hostApproval],
                ['Meeting point hidden until approved', true],
                ['Minimum 2 attendees to confirm run', true],
                ['Phone-verified runners only', true],
              ].map(([t, on]) => (
                <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Icon name="check" size={14} color={on ? PACER.lime : PACER.textSubtle}/>
                  <span style={{ fontSize: 13, color: on ? PACER.text : PACER.textSubtle }}>{t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{
          flexShrink: 0, padding: `14px 20px ${14 + SCREEN_BOTTOM}px`,
          background: `linear-gradient(180deg, rgba(10,12,10,0), ${PACER.bg} 30%)`,
          display: 'flex', gap: 10,
        }}>
          <Btn variant="secondary" size="lg" style={{ flex: 1 }} onClick={() => setStep(0)}>
            Edit
          </Btn>
          <Btn variant="primary" size="lg" style={{ flex: 2 }} onClick={() => setStep(2)}>
            Publish run
          </Btn>
        </div>
      </div>
    );
  }

  // --- Form step ---
  return (
    <div style={{ background: PACER.bg, height: '100%', color: PACER.text, fontFamily: PACER.font, display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
      {/* Top bar */}
      <div style={{
        flexShrink: 0, padding: `${SCREEN_TOP}px 16px 12px`, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={() => nav('home')} style={{
          width: 40, height: 40, borderRadius: 12,
          background: 'rgba(255,255,255,0.04)', border: `1px solid ${PACER.border}`,
          color: PACER.text, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="close" size={20} color={PACER.text}/>
        </button>
        <div style={{ fontSize: 16, fontWeight: 600 }}>{editMode ? 'Edit run' : 'New run'}</div>
        <div style={{ width: 40 }}/>
      </div>

      <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 20px 0' }}>
        {/* Title */}
        <FormSection label="Title">
          <input value={title} onChange={e => setTitle(e.target.value)} style={{
            width: '100%', boxSizing: 'border-box',
            background: PACER.inset, border: `1px solid ${PACER.border}`,
            borderRadius: 14, padding: '14px 16px',
            color: PACER.text, fontFamily: PACER.font, fontSize: 16, fontWeight: 500,
            outline: 'none',
          }}/>
        </FormSection>

        {/* Location */}
        <FormSection label="Area" hint="Public spaces only">
          <div onClick={() => setShowMapPicker(true)} style={{
            background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14,
            padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
          }}>
            <Icon name="pin" size={16} color={PACER.lime}/>
            <span style={{ flex: 1, fontSize: 15, color: PACER.text }}>{area}</span>
            <Icon name="chevR" size={14} color={PACER.textMute}/>
          </div>
          <div style={{ fontSize: 11.5, color: PACER.textMute, marginTop: 8, lineHeight: 1.5, display: 'flex', alignItems: 'flex-start', gap: 6 }}>
            <Icon name="lock" size={11} color={PACER.textMute} style={{ marginTop: 2 }}/>
            Exact meeting point shown only after you approve someone.
          </div>
        </FormSection>

        {/* Date + Time */}
        <FormSection label="When">
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{
              flex: 1, background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14,
              padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <Icon name="cal" size={16} color={PACER.textDim}/>
              <span style={{ fontSize: 15, fontWeight: 500 }}>{date}</span>
            </div>
            <div style={{
              flex: 1, background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14,
              padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <Icon name="clock" size={16} color={PACER.textDim}/>
              <span style={{ fontFamily: PACER.mono, fontSize: 15, fontWeight: 500 }}>{time}</span>
            </div>
          </div>
        </FormSection>

        {/* Distance */}
        <FormSection label="Distance">
          <SegmentedControl
            options={['3K', '5K', '10K', 'Custom']}
            value={distance} onChange={setDistance} mono
          />
          {distance === 'Custom' && (
            <div style={{ marginTop: 8 }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                background: PACER.inset,
                border: `1px solid ${customDistError ? 'rgba(255,80,80,0.5)' : PACER.border}`,
                borderRadius: 12, padding: '0 14px', height: 46,
              }}>
                <input
                  type="text"
                  inputMode="numeric"
                  placeholder="Distance in km (1–50)"
                  value={customDistance}
                  onChange={e => setCustomDistance(e.target.value.replace(/[^\d]/g, ''))}
                  style={{
                    flex: 1, background: 'transparent', border: 'none', outline: 'none',
                    fontFamily: PACER.mono, fontSize: 14, color: PACER.text,
                    caretColor: PACER.lime,
                  }}
                />
                {customDistance !== '' && !customDistError && (
                  <span style={{ fontFamily: PACER.mono, fontSize: 12, color: PACER.textMute }}>km</span>
                )}
              </div>
              {customDistError && (
                <div style={{
                  marginTop: 6, fontFamily: PACER.font, fontSize: 12,
                  color: 'rgba(255,100,100,0.9)', paddingLeft: 4,
                }}>
                  Enter a distance between 1 and 50 km
                </div>
              )}
            </div>
          )}
        </FormSection>

        {/* Pace */}
        <FormSection label="Pace range">
          <PaceRangeSlider min="6:00" max="6:45"/>
        </FormSection>

        {/* Group size */}
        <FormSection label="Group size" hint={`${groupSize} runners`}>
          <div style={{
            background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14,
            padding: '14px 16px',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              <span style={{ fontFamily: PACER.mono, fontSize: 22, fontWeight: 500 }}>{groupSize}</span>
              <span style={{ fontFamily: PACER.font, fontSize: 13, color: PACER.textMute }}>including you</span>
              <span style={{ flex: 1 }}/>
              <span style={{ fontFamily: PACER.font, fontSize: 10.5, color: PACER.textSubtle, letterSpacing: 0.5 }}>MIN 2 · MAX 12</span>
            </div>
            <input type="range" min="2" max="12" value={groupSize}
              onChange={e => setGroupSize(parseInt(e.target.value))}
              style={{
                width: '100%', accentColor: PACER.lime,
                appearance: 'none', WebkitAppearance: 'none',
                height: 4, background: 'rgba(255,255,255,0.12)', borderRadius: 99,
              }}/>
          </div>
        </FormSection>

        {/* Visibility */}
        <FormSection label="Visibility">
          <SegmentedControl
            options={ME.gender === 'female'
              ? [{ value: 'public', label: 'Public' }, { value: 'women-only', label: 'Women-only' }]
              : [{ value: 'public', label: 'Public' }]
            }
            value={visibility} onChange={setVisibility}
          />
          {visibility === 'women-only' && (
            <div style={{
              marginTop: 10, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 8,
              background: PACER.magentaSoft, border: `1px solid ${PACER.magentaBorder}`,
              borderRadius: 10, fontSize: 12, color: PACER.magenta,
            }}>
              <Icon name="shield" size={13} color={PACER.magenta}/>
              Only women will see this run. Verified at sign-up.
            </div>
          )}
        </FormSection>

        {/* Approval toggle */}
        <FormSection label="Joining">
          <div style={{
            background: PACER.inset, border: `1px solid ${PACER.border}`, borderRadius: 14,
            padding: '14px 16px',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 14.5, fontWeight: 500, marginBottom: 2 }}>Host approval</div>
                <div style={{ fontSize: 11.5, color: PACER.textMute }}>You approve each joiner</div>
              </div>
              <button onClick={() => setHostApproval(!hostApproval)} style={{
                width: 44, height: 26, borderRadius: 99, border: 'none',
                background: hostApproval ? PACER.lime : 'rgba(255,255,255,0.1)',
                position: 'relative', cursor: 'pointer', transition: 'all .15s',
              }}>
                <div style={{
                  position: 'absolute', top: 2, left: hostApproval ? 20 : 2,
                  width: 22, height: 22, borderRadius: '50%',
                  background: hostApproval ? PACER.limeInk : '#fff', transition: 'left .15s',
                }}/>
              </button>
            </div>
          </div>
        </FormSection>

        {/* Host note */}
        <FormSection label="Note from you" hint="Optional · 20 words max">
          <div style={{ position: 'relative' }}>
            <textarea
              value={hostNote}
              onChange={e => setHostNote(e.target.value)}
              placeholder="e.g. Stick around for coffee after, café is nearby."
              style={{
                width: '100%', boxSizing: 'border-box', minHeight: 88,
                background: PACER.inset,
                border: `1px solid ${hostNoteOver ? 'rgba(255,100,100,0.5)' : PACER.border}`,
                borderRadius: 14, padding: '12px 16px 28px',
                color: PACER.text, fontFamily: PACER.font, fontSize: 14.5, lineHeight: 1.5,
                outline: 'none', resize: 'none',
              }}
            />
            <div style={{
              position: 'absolute', bottom: 10, right: 14,
              fontFamily: PACER.mono, fontSize: 10.5,
              color: hostNoteOver ? 'rgba(255,100,100,0.9)' : PACER.textSubtle,
            }}>
              {hostNoteWords}/{HOST_NOTE_MAX_WORDS}
            </div>
          </div>
          {hostNoteOver && (
            <div style={{ marginTop: 6, fontSize: 12, color: 'rgba(255,100,100,0.9)', paddingLeft: 4 }}>
              Keep it to 20 words
            </div>
          )}
        </FormSection>

        <div style={{ height: 20 }}/>
      </div>

      {/* CTA */}
      <div style={{
        flexShrink: 0, padding: `14px 20px ${14 + SCREEN_BOTTOM}px`,
        background: `linear-gradient(180deg, rgba(10,12,10,0), ${PACER.bg} 30%)`,
      }}>
        <Btn variant="primary" size="lg" style={{ width: '100%' }} onClick={() => setStep(1)}>
          {editMode ? 'Preview changes' : 'Preview run'}
        </Btn>
      </div>

      {/* Map picker overlay */}
      {showMapPicker && (
        <MapPicker
          initial={area}
          onConfirm={(name) => { setArea(name); setShowMapPicker(false); }}
          onClose={() => setShowMapPicker(false)}
        />
      )}
    </div>
  );
}

Object.assign(window, { CreateScreen });
