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

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, max, onChange }) {
  // Render: two-thumb pace track with tick marks
  // Pace values 4:30 to 8:00 -> map to 0..14 (30-sec increments)
  const ticks = ['4:30','5:00','5:30','6:00','6:30','7:00','7:30','8:00'];
  const idx = (v) => ticks.indexOf(v);
  const minIdx = idx(min), maxIdx = idx(max);
  const leftPct = (minIdx / (ticks.length - 1)) * 100;
  const rightPct = (maxIdx / (ticks.length - 1)) * 100;
  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,
          }}>{min}–{max}<span style={{ color: PACER.textMute, fontSize: 14 }}>/km</span></div>
          <div style={{ fontFamily: PACER.font, fontSize: 11.5, color: PACER.textMute, marginTop: 2 }}>
            That’s 5K in ~{Math.round((parseInt(min) * 60 + parseInt(min.split(':')[1])) * 5 / 60)}-{Math.round((parseInt(max) * 60 + parseInt(max.split(':')[1])) * 5 / 60)} 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>
      {/* track */}
      <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: `${leftPct}%`, width: `${rightPct - leftPct}%`,
          height: 4, background: PACER.lime, borderRadius: 99,
        }}/>
        {/* thumbs */}
        {[leftPct, rightPct].map((p, i) => (
          <div key={i} style={{
            position: 'absolute', top: 8, left: `${p}%`, transform: 'translateX(-50%)',
            width: 16, height: 16, borderRadius: '50%',
            background: PACER.lime, border: `3px solid ${PACER.bg}`,
            boxShadow: `0 0 0 1px ${PACER.lime}`,
          }}/>
        ))}
      </div>
      {/* tick labels */}
      <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 }) {
  const [title, setTitle] = React.useState('Easy Friday shakeout');
  const [area, setArea] = React.useState('Clifton Down');
  const [distance, setDistance] = React.useState('5K');
  const [level, setLevel] = React.useState('Beginner');
  const [date, setDate] = React.useState('Fri 22');
  const [time, setTime] = React.useState('18:30');
  const [groupSize, setGroupSize] = React.useState(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' }}>
          Run published
        </div>
        <div style={{ fontSize: 14, color: PACER.textDim, textAlign: 'center', marginBottom: 28, lineHeight: 1.5 }}>
          Folks in {area.split(' ')[0]} at your pace will see it now.<br/>
          We’ll ping you when someone requests.
        </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, minHeight: '100%', color: PACER.text, fontFamily: PACER.font, position: 'relative' }}>
        <div style={{
          padding: '54px 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={{ padding: '12px 20px 160px' }}>
          <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={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '14px 20px 38px',
          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, minHeight: '100%', color: PACER.text, fontFamily: PACER.font, position: 'relative' }}>
      {/* Top bar */}
      <div style={{
        padding: '54px 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 }}>New run</div>
        <div style={{ width: 40 }}/>
      </div>

      <div style={{ padding: '12px 20px 160px' }}>
        {/* 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 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>
            <span style={{ fontFamily: PACER.mono, fontSize: 11, color: PACER.textMute }}>BS8</span>
          </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
          />
        </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={[
              { value: 'public', label: 'Public' },
              { value: 'women-only', label: 'Women-only' },
            ]}
            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-verified accounts will see this run.
            </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>

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

      {/* CTA */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 20px 38px',
        background: `linear-gradient(180deg, rgba(10,12,10,0), ${PACER.bg} 30%)`,
      }}>
        <Btn variant="primary" size="lg" style={{ width: '100%' }} onClick={() => setStep(1)}>
          Preview run
        </Btn>
      </div>
    </div>
  );
}

Object.assign(window, { CreateScreen });
