// app.jsx — main prototype state machine + iOS frame wrapper

function TabBar({ active, onChange, hasNew }) {
  const tabs = [
    { id: 'home', icon: 'home', label: 'Runs' },
    { id: 'create', icon: 'plus', label: 'Create' },
    { id: 'hostIndex', icon: 'users', label: 'Hosting' },
    { id: 'profile', icon: 'user', label: 'You' },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 20,
      padding: `8px 16px ${SCREEN_BOTTOM}px`,
      background: `linear-gradient(180deg, rgba(10,12,10,0.7), ${PACER.bg} 60%)`,
      backdropFilter: 'blur(20px)',
      WebkitBackdropFilter: 'blur(20px)',
      borderTop: `1px solid ${PACER.border}`,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-around' }}>
        {tabs.map(t => {
          const sel = active === t.id;
          const isCreate = t.id === 'create';
          if (isCreate) {
            return (
              <button key={t.id} onClick={() => onChange(t.id)} style={{
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                background: 'transparent', border: 'none', cursor: 'pointer',
                padding: '4px 12px', flex: 1,
              }}>
                <div style={{
                  width: 44, height: 30, borderRadius: 10,
                  background: PACER.lime, color: PACER.limeInk,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: '0 6px 18px rgba(212,255,58,0.25)',
                }}>
                  <Icon name="plus" size={20} color={PACER.limeInk}/>
                </div>
                <span style={{ fontSize: 10.5, fontWeight: 500, color: PACER.textDim, fontFamily: PACER.font }}>
                  {t.label}
                </span>
              </button>
            );
          }
          return (
            <button key={t.id} onClick={() => onChange(t.id)} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: '6px 12px', flex: 1, position: 'relative',
            }}>
              <Icon name={t.icon} size={22} color={sel ? PACER.text : PACER.textMute}/>
              <span style={{ fontSize: 10.5, fontWeight: sel ? 600 : 500,
                color: sel ? PACER.text : PACER.textMute, fontFamily: PACER.font }}>
                {t.label}
              </span>
              {hasNew && t.id === 'hostIndex' && (
                <span style={{
                  position: 'absolute', top: 4, right: '32%', width: 7, height: 7, borderRadius: '50%',
                  background: PACER.lime,
                }}/>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Profile screen — incl. "Your runs" (joined + pending)
// ─────────────────────────────────────────────────────────────
function ProfileMyRunRow({ entry, onClick }) {
  const run = RUNS.find(r => r.id === entry.runId);
  const host = USERS[run.host];
  const isPending = entry.status === 'pending';
  return (
    <div onClick={onClick} style={{
      background: PACER.card,
      border: `1px solid ${isPending ? 'rgba(255,181,71,0.25)' : PACER.border}`,
      borderRadius: 14, padding: 12, cursor: 'pointer',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      {/* Status dot */}
      <div style={{
        width: 8, height: 8, borderRadius: '50%',
        background: isPending ? PACER.amber : PACER.lime,
        boxShadow: `0 0 0 4px ${isPending ? 'rgba(255,181,71,0.15)' : PACER.limeSoft}`,
        flexShrink: 0,
      }}/>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontFamily: PACER.font, fontSize: 14, fontWeight: 600, color: PACER.text }}>
            {run.title}
          </span>
          {isPending && (
            <span style={{
              fontFamily: PACER.font, fontSize: 9.5, fontWeight: 600,
              color: PACER.amber, letterSpacing: 1, textTransform: 'uppercase',
            }}>Pending</span>
          )}
        </div>
        <div style={{ fontFamily: PACER.mono, fontSize: 11, color: PACER.textMute, marginTop: 2 }}>
          {run.dateLong} · {run.area}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 6 }}>
          <Avatar name={host.name} size={16}/>
          <span style={{ fontFamily: PACER.font, fontSize: 11, color: PACER.textDim }}>
            {isPending ? 'Awaiting ' : ''}{host.name.split(' ')[0]}
          </span>
        </div>
      </div>
      <Icon name="chev" size={14} color={PACER.textSubtle}/>
    </div>
  );
}

function ProfileScreen({ nav, onSelectRun }) {
  const stats = [
    { l: 'Runs attended', v: ME.attended },
    { l: 'Crew met', v: 12 },
  ];
  // Split & date-sort my runs
  const dateRank = (r) => RUNS.findIndex(x => x.id === r.runId); // their order in RUNS roughly chronological
  const going  = MY_RUNS.filter(r => r.status === 'going').sort((a, b) => dateRank(a) - dateRank(b));
  const pending = MY_RUNS.filter(r => r.status === 'pending').sort((a, b) => dateRank(a) - dateRank(b));

  return (
    <div style={{ background: PACER.bg, height: '100%', overflowY: 'auto', color: PACER.text, fontFamily: PACER.font, position: 'relative' }}>
      {/* Settings button (top-right) */}
      <button onClick={() => nav && nav('settings')} style={{
        position: 'absolute', top: SCREEN_TOP, right: 20, zIndex: 5,
        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="gear" size={18} color={PACER.textDim}/>
      </button>

      <div style={{ padding: `${SCREEN_TOP}px 20px ${60 + SCREEN_BOTTOM}px` }}>
        {/* Top: identity */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Avatar name={ME.firstName} size={72} photo/>
          <div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.5 }}>{ME.firstName}</div>
            <div style={{ fontSize: 13, color: PACER.textDim, fontFamily: PACER.mono, marginTop: 2 }}>
              {ME.paceMin}–{ME.paceMax}/km · {ME.neighborhood}
            </div>
            <div style={{
              marginTop: 6, display: 'inline-flex', gap: 6, alignItems: 'center',
              fontSize: 11, color: PACER.lime, fontWeight: 500,
              background: PACER.limeSoft, padding: '3px 8px', borderRadius: 99,
              border: `1px solid ${PACER.limeBorder}`,
            }}>
              <Icon name="phone" size={10} color={PACER.lime}/>
              Phone verified
            </div>
          </div>
        </div>

        {/* Stats */}
        <div style={{
          marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
        }}>
          {stats.map(s => (
            <div key={s.l} style={{
              background: PACER.card, border: `1px solid ${PACER.border}`,
              borderRadius: 14, padding: '14px 14px',
            }}>
              <div style={{ fontFamily: PACER.mono, fontSize: 22, fontWeight: 500, color: PACER.text }}>{s.v}</div>
              <div style={{ fontSize: 11, color: PACER.textMute, marginTop: 4 }}>{s.l}</div>
            </div>
          ))}
        </div>

        {/* Your runs */}
        <div style={{ marginTop: 26 }}>
          <div style={{
            display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 600, color: PACER.textMute,
              letterSpacing: 1.4, textTransform: 'uppercase',
            }}>Your runs</div>
            <span style={{ fontFamily: PACER.mono, fontSize: 11, color: PACER.textSubtle }}>
              {going.length + pending.length} upcoming
            </span>
          </div>

          {pending.length > 0 && (
            <>
              <div style={{
                fontFamily: PACER.font, fontSize: 12, color: PACER.amber, fontWeight: 600,
                margin: '8px 0 8px', display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name="clock" size={12} color={PACER.amber}/>
                Awaiting approval · <span style={{ fontFamily: PACER.mono }}>{pending.length}</span>
              </div>
              <div style={{ display: 'grid', gap: 8, marginBottom: 16 }}>
                {pending.map(r => (
                  <ProfileMyRunRow key={r.runId} entry={r}
                    onClick={() => onSelectRun && onSelectRun(r.runId, 'pending')}/>
                ))}
              </div>
            </>
          )}

          {going.length > 0 && (
            <>
              <div style={{
                fontFamily: PACER.font, fontSize: 12, color: PACER.lime, fontWeight: 600,
                margin: '8px 0 8px', display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name="check" size={12} color={PACER.lime}/>
                Going · <span style={{ fontFamily: PACER.mono }}>{going.length}</span>
              </div>
              <div style={{ display: 'grid', gap: 8 }}>
                {going.map(r => (
                  <ProfileMyRunRow key={r.runId} entry={r}
                    onClick={() => onSelectRun && onSelectRun(r.runId, 'approved')}/>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Pace + distance summary */}
        <div style={{ marginTop: 26 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: PACER.textMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 10 }}>
            Your defaults
          </div>
          <div style={{ display: 'grid', gap: 8 }}>
            {[
              ['Pace', `${ME.paceMin}–${ME.paceMax}/km`, 'pace'],
              ['Distance', ME.distancePref, 'run'],
              ['Neighborhood', ME.neighborhood, 'pin'],
            ].map(([l, v, icon]) => (
              <div key={l} style={{
                background: PACER.card, border: `1px solid ${PACER.border}`,
                borderRadius: 14, padding: '14px 16px',
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <Icon name={icon} size={18} color={PACER.textDim}/>
                <span style={{ flex: 1, fontSize: 14 }}>{l}</span>
                <span style={{ fontFamily: PACER.mono, fontSize: 13, color: PACER.textDim }}>{v}</span>
                <Icon name="chev" size={14} color={PACER.textSubtle}/>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Inspect mode — click any element to copy its outerHTML
// ─────────────────────────────────────────────────────────────
function InspectMode() {
  const [active, setActive] = React.useState(false);
  const btnRef = React.useRef(null);
  const lastHighlightRef = React.useRef(null);

  const clearHighlight = () => {
    if (lastHighlightRef.current) {
      lastHighlightRef.current.style.outline = '';
      lastHighlightRef.current.style.outlineOffset = '';
      lastHighlightRef.current = null;
    }
  };

  React.useEffect(() => {
    if (!active) return;

    document.body.style.cursor = 'crosshair';

    const onMove = (e) => {
      if (btnRef.current && btnRef.current.contains(e.target)) {
        clearHighlight();
        return;
      }
      clearHighlight();
      lastHighlightRef.current = e.target;
      e.target.style.outline = '2px solid rgba(212,255,58,0.85)';
      e.target.style.outlineOffset = '-1px';
    };

    const onClick = (e) => {
      if (btnRef.current && btnRef.current.contains(e.target)) return;
      e.preventDefault();
      e.stopPropagation();
      clearHighlight();
      navigator.clipboard.writeText(e.target.outerHTML);
      setActive(false);
    };

    document.addEventListener('mousemove', onMove, true);
    document.addEventListener('click', onClick, true);

    return () => {
      document.body.style.cursor = '';
      clearHighlight();
      document.removeEventListener('mousemove', onMove, true);
      document.removeEventListener('click', onClick, true);
    };
  }, [active]);

  const btn = (
    <button
      ref={btnRef}
      onClick={() => setActive(a => !a)}
      style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 2147483647,
        height: 28, padding: '0 10px',
        background: active ? PACER.lime : 'rgba(0,0,0,0.72)',
        color: active ? PACER.limeInk : PACER.textDim,
        border: active ? 'none' : `1px solid ${PACER.border}`,
        borderRadius: 99,
        fontFamily: PACER.mono, fontSize: 11, fontWeight: 600,
        cursor: 'pointer',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        letterSpacing: 0.3,
        userSelect: 'none',
      }}
    >
      {active ? '✕ cancel' : '⌖ inspect'}
    </button>
  );

  return ReactDOM.createPortal(btn, document.body);
}

// ─────────────────────────────────────────────────────────────
// Prototype disclaimer splash
// ─────────────────────────────────────────────────────────────
function SplashScreen({ onDismiss }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      background: PACER.bg,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      padding: '32px 28px',
      textAlign: 'center',
    }}>
      <div style={{
        width: 64, height: 64, borderRadius: 18,
        background: PACER.lime, marginBottom: 28,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="play" size={30} color={PACER.limeInk}/>
      </div>

      <div style={{ fontSize: 24, fontWeight: 700, color: PACER.text, fontFamily: PACER.font, marginBottom: 10, lineHeight: 1.2 }}>
        This is a design prototype
      </div>

      <div style={{ fontSize: 15, color: PACER.textDim, fontFamily: PACER.font, lineHeight: 1.6, marginBottom: 12, maxWidth: 280 }}>
        You&apos;re looking at an interactive mockup — not a real app.
      </div>

      <div style={{ fontSize: 15, color: PACER.textDim, fontFamily: PACER.font, lineHeight: 1.6, marginBottom: 40, maxWidth: 280 }}>
        There&apos;s nothing to sign up for. Just <strong style={{ color: PACER.text }}>tap around and explore</strong> the concept.
      </div>

      <button onClick={onDismiss} style={{
        width: '100%', maxWidth: 280, padding: '16px 0',
        background: PACER.lime, color: PACER.limeInk,
        border: 'none', borderRadius: 14,
        fontSize: 16, fontWeight: 700, fontFamily: PACER.font,
        cursor: 'pointer',
      }}>
        Got it, let me explore
      </button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Main app
// ─────────────────────────────────────────────────────────────
function App() {
  // Screens: home | runDetail | joinRequest | chat | create | hostIndex | hostRequests | profile
  const [screen, setScreen] = React.useState('home');
  const [selectedRunId, setSelectedRunId] = React.useState('r1');
  const [runState, setRunState] = React.useState('browse'); // browse | pending | approved
  const [decisions, setDecisions] = React.useState({});
  const [completedOnboarding, setCompletedOnboarding] = React.useState(false);
  const [editRunId, setEditRunId] = React.useState(null);
  const [showSplash, setShowSplash] = React.useState(true);

  const run = RUNS.find(r => r.id === selectedRunId);

  const nav = (s) => setScreen(s);

  const onSelectRun = (id, initialState) => {
    setSelectedRunId(id);
    const run = RUNS.find(r => r.id === id);
    setRunState(initialState || (run && run.openToJoin ? 'open' : 'browse'));
    setScreen('runDetail');
  };

  // Tap "Request to join" on the run detail → opens the message screen
  const handleRequestJoin = () => {
    setScreen('joinRequest');
  };

  // Send the request → go to pending and stay there
  const handleSendRequest = () => {
    setRunState('pending');
    setScreen('runDetail');
  };

  const handleDecide = (user, decision) => {
    setDecisions(prev => ({ ...prev, [user]: decision }));
  };

  if (showSplash) {
    return <SplashScreen onDismiss={() => setShowSplash(false)}/>;
  }

  if (!completedOnboarding) {
    return <OnboardingScreen onDone={() => { setCompletedOnboarding(true); setScreen('home'); }}/>;
  }

  const showTabBar = ['home', 'profile', 'hostIndex'].includes(screen);
  const hasNewRequest = MY_HOSTED.some(r => r.pending > 0);

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', background: PACER.bg }}>
      {screen === 'home' && <HomeScreen nav={nav} onSelectRun={onSelectRun} hasNewRequest={hasNewRequest}/>}
      {screen === 'runDetail' && (
        <RunDetailScreen run={run} state={runState} nav={nav}
          onRequestJoin={handleRequestJoin}
          onOpenChat={() => setScreen('chat')}
        />
      )}
      {screen === 'joinRequest' && (
        <JoinRequestScreen run={run} nav={nav} onSend={handleSendRequest}/>
      )}
      {screen === 'chat' && <ChatScreen run={run} nav={() => setScreen('runDetail')}/>}
      {screen === 'create' && <CreateScreen nav={setScreen} onPublish={() => { setEditRunId(null); setScreen(editRunId ? 'hostRequests' : 'home'); }} initialRun={editRunId ? RUNS.find(r => r.id === editRunId) : null} editMode={!!editRunId}/>}
      {screen === 'hostIndex' && (
        <HostIndexScreen nav={setScreen} onSelectHostedRun={() => setScreen('hostRequests')}/>
      )}
      {screen === 'hostRequests' && (
        <HostRequestsScreen
          nav={() => setScreen('hostIndex')}
          decisions={decisions}
          onDecide={handleDecide}
          onViewRun={() => { setSelectedRunId('r1'); setRunState('approved'); setScreen('runDetail'); }}
          onOpenChat={() => { setSelectedRunId('r1'); setScreen('chat'); }}
          onEditRun={() => { setEditRunId('r1'); setScreen('create'); }}
        />
      )}
      {screen === 'profile' && <ProfileScreen nav={setScreen} onSelectRun={onSelectRun}/>}
      {screen === 'settings' && <SettingsScreen nav={setScreen}/>}

      {showTabBar && <TabBar active={screen} onChange={setScreen} hasNew={hasNewRequest}/>}

      {/* Floating debug button to restart onboarding */}
      <button onClick={() => setCompletedOnboarding(false)} style={{
        position: 'absolute', top: 64, right: 70, zIndex: 100,
        padding: '4px 8px', fontSize: 9.5, letterSpacing: 0.5,
        background: 'rgba(0,0,0,0.6)', color: PACER.lime,
        border: `1px solid ${PACER.limeBorder}`, borderRadius: 99,
        fontFamily: PACER.mono, cursor: 'pointer', opacity: 0,
        transition: 'opacity .2s',
      }}
      onMouseEnter={e => e.currentTarget.style.opacity = 1}
      onMouseLeave={e => e.currentTarget.style.opacity = 0}>
        ↺ onboarding
      </button>
    </div>
  );
}

Object.assign(window, { App, TabBar, ProfileScreen, ProfileMyRunRow, InspectMode });
