// screens-home.jsx — Home feed: "Runs near you"
// Required globals: PACER, Chip, Avatar, Btn, StatRow, Icon, Card, RUNS, USERS, ME

const DIST_FILTERS = ['2K+', '5K+', '10K+'];
const ALL_FILTERS = ME.gender === 'female' ? ['Women-only', ...DIST_FILTERS] : DIST_FILTERS;

function RunCard({ run, onClick, compact = false }) {
  const host = USERS[run.host];
  const isFull = run.joined.length >= run.capacity;
  const womenOnly = run.womenOnly;

  return (
    <div onClick={onClick} style={{
      background: PACER.card,
      border: `1px solid ${PACER.border}`,
      borderRadius: 18,
      padding: 16,
      cursor: 'pointer',
      transition: 'border-color .15s',
      position: 'relative',
    }}
    onMouseEnter={e => e.currentTarget.style.borderColor = PACER.borderStrong}
    onMouseLeave={e => e.currentTarget.style.borderColor = PACER.border}>

      {/* Title row | time + day */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 8 }}>
        <div style={{
          fontFamily: PACER.font, fontSize: 18, fontWeight: 600,
          color: PACER.text, letterSpacing: -0.3, lineHeight: 1.2,
        }}>{run.title}</div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontFamily: PACER.mono, fontSize: 13, color: PACER.text, fontWeight: 500 }}>
            {run.time}
          </div>
        </div>
      </div>

      {/* Distance + pace */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 6 }}>
        <span style={{ fontFamily: PACER.mono, fontSize: 14, color: PACER.text, fontWeight: 500 }}>
          {run.distance}
        </span>
        <span style={{ fontFamily: PACER.mono, fontSize: 13, color: PACER.textDim }}>
          {run.paceMin}–{run.paceMax}<span style={{ color: PACER.textSubtle }}>/km</span>
        </span>
      </div>

      {/* Location */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 14 }}>
        <Icon name="pin" size={13} color={PACER.textMute}/>
        <span style={{ fontFamily: PACER.font, fontSize: 13, color: PACER.textDim }}>
          {run.area}
        </span>
      </div>

      {/* Bottom: host + chips + capacity */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
          <Avatar name={host.name} size={26}/>
          <span style={{ fontFamily: PACER.font, fontSize: 12.5, color: PACER.textDim, whiteSpace: 'nowrap' }}>
            {host.name.split(' ')[0]}
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          {womenOnly && <Chip tone="magenta" size="xs">Women-only</Chip>}
          {run.openToJoin && <Chip tone="lime" size="xs">Public</Chip>}
          <Chip tone={isFull ? 'amber' : 'default'} size="xs">
            <span style={{ fontFamily: PACER.mono }}>{run.joined.length}</span>
            <span style={{ opacity: 0.5 }}>/</span>
            <span style={{ fontFamily: PACER.mono }}>{run.capacity}</span>
          </Chip>
        </div>
      </div>
    </div>
  );
}

// Featured "right now" card — extra emphasis with neon edge
function FeaturedRunCard({ run, onClick }) {
  const host = USERS[run.host];
  const isFull = run.joined.length >= run.capacity;

  return (
    <div onClick={onClick} style={{
      background: `linear-gradient(180deg, rgba(212,255,58,0.05) 0%, rgba(212,255,58,0) 60%), ${PACER.card}`,
      border: `1px solid ${PACER.limeBorder}`,
      borderRadius: 22, padding: 18,
      cursor: 'pointer', position: 'relative', overflow: 'hidden',
    }}>
      {/* live ribbon row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 14 }}>
        <span style={{
          width: 6, height: 6, borderRadius: 99, background: PACER.lime,
          boxShadow: `0 0 0 4px ${PACER.limeSoft}`,
        }}/>
        <span style={{
          fontFamily: PACER.font, fontSize: 11, color: PACER.lime,
          letterSpacing: 1.2, textTransform: 'uppercase', fontWeight: 600,
        }}>Starting in 2h</span>
        <span style={{ flex: 1 }}/>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontFamily: PACER.mono, fontSize: 13, color: PACER.text, fontWeight: 500 }}>
            {run.time}
          </div>
          <div style={{ fontFamily: PACER.font, fontSize: 11.5, color: PACER.textMute, marginTop: 1 }}>
            Today
          </div>
        </div>
      </div>

      {/* Title */}
      <div style={{
        fontFamily: PACER.font, fontSize: 22, fontWeight: 600,
        color: PACER.text, letterSpacing: -0.5, marginBottom: 8, lineHeight: 1.15,
      }}>{run.title}</div>

      {/* Distance + pace */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, marginBottom: 6 }}>
        <span style={{ fontFamily: PACER.mono, fontSize: 16, color: PACER.text, fontWeight: 500 }}>
          {run.distance}
        </span>
        <span style={{ fontFamily: PACER.mono, fontSize: 13, color: PACER.textDim }}>
          {run.paceMin}–{run.paceMax}/km
        </span>
      </div>

      {/* Location */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 16 }}>
        <Icon name="pin" size={13} color={PACER.textMute}/>
        <span style={{ fontFamily: PACER.font, fontSize: 13, color: PACER.textDim }}>
          {run.area}
        </span>
      </div>

      {/* Bottom: avatar stack + host name + capacity */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          {run.joined.slice(0, 3).map((u, i) => (
            <div key={u} style={{ marginLeft: i === 0 ? 0 : -8, border: `2px solid ${PACER.card}`, borderRadius: '50%' }}>
              <Avatar name={USERS[u].name} size={28}/>
            </div>
          ))}
          <span style={{ fontFamily: PACER.font, fontSize: 12.5, color: PACER.textDim, marginLeft: 10 }}>
            {host.name.split(' ')[0]}
          </span>
        </div>
        <Chip tone={isFull ? 'amber' : 'default'} size="xs">
          <span style={{ fontFamily: PACER.mono }}>{run.joined.length}</span>
          <span style={{ opacity: 0.5 }}>/</span>
          <span style={{ fontFamily: PACER.mono }}>{run.capacity}</span>
        </Chip>
      </div>
    </div>
  );
}

function HomeScreen({ nav, onSelectRun, hasNewRequest }) {
  const [activeFilter, setFilter] = React.useState(null);

  // Base pool: women-only runs are invisible to non-female users
  const isFemale = ME.gender === 'female';
  const visibleRuns = RUNS.filter(r => isFemale || !r.womenOnly);

  // Apply active filter
  const filteredRuns = visibleRuns.filter(r => {
    if (!activeFilter) return true;
    if (activeFilter === 'Women-only') return r.womenOnly;
    if (activeFilter === '2K+')  return parseInt(r.distance) >= 2;
    if (activeFilter === '5K+')  return parseInt(r.distance) >= 5;
    if (activeFilter === '10K+') return parseInt(r.distance) >= 10;
    return true;
  });

  // Featured = first run with `when === 'Today'` from the filtered pool
  const featured = activeFilter ? null : visibleRuns.find(r => r.when === 'Today');
  const others = filteredRuns.filter(r => r !== featured);

  // Group by when
  const groups = {};
  others.forEach(r => { (groups[r.when] = groups[r.when] || []).push(r); });

  return (
    <div style={{ background: PACER.bg, height: '100%', overflowY: 'auto', color: PACER.text, fontFamily: PACER.font }}>
      {/* Header */}
      <div style={{ padding: `${SCREEN_TOP}px 20px 8px` }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            <div style={{
              width: 30, height: 30, borderRadius: 9, background: PACER.lime,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="run" size={18} color={PACER.limeInk}/>
            </div>
            <div style={{
              fontFamily: PACER.font, fontSize: 19, fontWeight: 700,
              letterSpacing: -0.5, color: PACER.text,
            }}>Run Crew</div>
          </div>
        </div>

        {/* Hero question */}
        <div style={{
          fontFamily: PACER.font, fontSize: 30, fontWeight: 600,
          letterSpacing: -1.1, color: PACER.text, lineHeight: 1.05,
          marginBottom: 4,
        }}>Runs near you</div>
        <div style={{
          fontFamily: PACER.font, fontSize: 14, color: PACER.textDim,
          letterSpacing: -0.1,
        }}>
          <span>{ME.neighborhood}</span>
        </div>
      </div>

      {/* Filter chips — horizontal scroll */}
      <div style={{
        display: 'flex', gap: 8, padding: '20px 20px 18px',
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        <button onClick={() => setFilter(null)} style={{
          height: 34, padding: '0 14px', borderRadius: 99,
          background: !activeFilter ? PACER.lime : 'transparent',
          border: `1px solid ${!activeFilter ? PACER.lime : PACER.border}`,
          color: !activeFilter ? PACER.limeInk : PACER.textDim,
          fontFamily: PACER.font, fontSize: 13, fontWeight: !activeFilter ? 600 : 500,
          cursor: 'pointer', flexShrink: 0, transition: 'all .15s',
        }}>All</button>
        {ALL_FILTERS.map(f => {
          const isWomen = f === 'Women-only';
          const isActive = f === activeFilter;
          return (
            <button key={f} onClick={() => setFilter(f === activeFilter ? null : f)} style={{
              height: 34, padding: '0 14px', borderRadius: 99,
              background: isActive ? (isWomen ? PACER.magenta : PACER.lime) : 'transparent',
              border: `1px solid ${isActive ? (isWomen ? PACER.magenta : PACER.lime) : (isWomen ? PACER.magentaBorder : PACER.border)}`,
              color: isActive ? (isWomen ? '#fff' : PACER.limeInk) : (isWomen ? PACER.magenta : PACER.textDim),
              fontFamily: PACER.font, fontSize: 13, fontWeight: isActive ? 600 : 500,
              cursor: 'pointer', flexShrink: 0, transition: 'all .15s',
            }}>{f}</button>
          );
        })}
      </div>

      {/* Featured today */}
      <div style={{ padding: '0 20px 24px' }}>
        {featured && <FeaturedRunCard run={featured} onClick={() => onSelectRun(featured.id)}/>}
      </div>

      {/* Grouped sections */}
      <div style={{ padding: '0 20px 120px' }}>
        {Object.entries(groups).map(([when, runs]) => (
          <div key={when} style={{ marginBottom: 22 }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
              marginBottom: 10,
            }}>
              <div style={{
                fontFamily: PACER.font, fontSize: 12, fontWeight: 600,
                color: PACER.textMute, textTransform: 'uppercase', letterSpacing: 1.4,
              }}>{when}</div>
            </div>
            <div style={{ display: 'grid', gap: 10 }}>
              {runs.map(r => (
                <RunCard key={r.id} run={r} onClick={() => onSelectRun(r.id)}/>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, RunCard, FeaturedRunCard });
