/* GoWithMe — full "Reviews & Stories" screen (pushed from Place Detail).
   Filter by type · sort · photo wall · contributor impact · all cards. */

/* contributor impact / gamification strip */
function ImpactStrip({ gamify = true }) {
  const me = HM.ME;
  const { cur, next } = HM.levelFor(me.points);
  const span = next ? next.at - cur.at : 1;
  const pct = next ? Math.min(100, ((me.points - cur.at) / span) * 100) : 100;
  return (
    <div style={{ background: T.navy, borderRadius: 18, padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
        <div style={{ position: 'relative' }}>
          <AuthorAvatar author={me} size={48} />
          <span style={{ position: 'absolute', bottom: -3, right: -3, minWidth: 20, height: 20, padding: '0 5px', borderRadius: 999, background: T.gold, color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `2px solid ${T.navy}` }}>L{me.level}</span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 15.5, color: '#fff' }}>{me.name}</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: SANS, fontSize: 12.5, color: T.gold, fontWeight: 700, marginTop: 1 }}>
            <Icon name="award" size={13} color={T.gold} />Level {cur.n} · {cur.name}
          </div>
        </div>
      </div>

      {gamify && (
        <div style={{ marginTop: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: SANS, fontSize: 12, color: 'rgba(255,255,255,0.6)', marginBottom: 6 }}>
            <span>{me.points.toLocaleString()} pts</span>
            {next && <span>{(next.at - me.points).toLocaleString()} pts to {next.name}</span>}
          </div>
          <div style={{ height: 7, borderRadius: 999, background: 'rgba(255,255,255,0.14)', overflow: 'hidden' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: T.gold, borderRadius: 999 }} />
          </div>
        </div>
      )}

      <div style={{ display: 'flex', marginTop: 15 }}>
        {[[me.counts.contributions, 'Contributions'], [fmtK(me.counts.helpful), 'Helpful votes'], [me.counts.photos, 'Photos']].map((s, i) => (
          <div key={i} style={{ flex: 1, textAlign: 'center', borderRight: i < 2 ? '1px solid rgba(255,255,255,0.12)' : 'none' }}>
            <div style={{ fontFamily: DISP, fontWeight: 800, fontSize: 20, color: '#fff' }}>{s[0]}</div>
            <div style={{ fontFamily: SANS, fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>{s[1]}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* horizontal photo wall */
function PhotoWall({ photos, count }) {
  if (!photos || !photos.length) return null;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 11 }}>
        <h2 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 20, color: T.ink, margin: 0 }}>Traveler photos</h2>
        <span style={{ fontFamily: SANS, fontSize: 13, color: T.muted, fontWeight: 600 }}>{count}</span>
      </div>
      <div style={{ display: 'flex', gap: 9, overflowX: 'auto', margin: '0 -22px', padding: '0 22px' }}>
        {photos.map((p, i) => (
          <div key={i} style={{ position: 'relative' }}>
            <Photo p={p} size={124} radius={14} />
            {p.by && <div style={{ position: 'absolute', left: 8, bottom: 8, fontFamily: SANS, fontSize: 10.5, fontWeight: 700, color: '#fff', background: 'rgba(8,18,32,0.55)', backdropFilter: 'blur(4px)', padding: '3px 8px', borderRadius: 7 }}>{p.by.split(' ')[0]}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

const SORTS = [
  { id: 'helpful', label: 'Most helpful' },
  { id: 'recent',  label: 'Most recent' },
  { id: 'high',    label: 'Highest rated' },
  { id: 'low',     label: 'Lowest rated' },
];

function CommunityScreen({ place, data, onBack, onWrite, aiLearning = true, gamify = true }) {
  const [filter, setFilter] = React.useState('all');
  const [sort, setSort] = React.useState('helpful');
  const [sortOpen, setSortOpen] = React.useState(false);

  const counts = React.useMemo(() => {
    const c = { all: data.items.length };
    HM.CTYPE_ORDER.forEach((t) => { c[t] = data.items.filter((i) => i.type === t).length; });
    return c;
  }, [data.items]);

  let list = filter === 'all' ? data.items : data.items.filter((i) => i.type === filter);
  list = [...list].sort((a, b) => {
    if (a.mine && !b.mine) return -1;              // your own contributions pin to top
    if (b.mine && !a.mine) return 1;
    if (sort === 'helpful') return (b.helpful || 0) - (a.helpful || 0);
    if (sort === 'high') return (b.rating || 0) - (a.rating || 0);
    if (sort === 'low') return (a.rating || 6) - (b.rating || 6);
    return 0; // recent = source order (new submissions prepend)
  });

  const filterChips = [{ id: 'all', label: 'All', icon: 'users' }].concat(
    HM.CTYPE_ORDER.map((t) => ({ id: t, label: HM.CTYPES[t].label, icon: HM.CTYPES[t].icon }))
  );

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.cream, position: 'relative' }}>
      {/* header */}
      <div style={{ background: T.navy, paddingBottom: 16, borderBottomLeftRadius: 26, borderBottomRightRadius: 26, flexShrink: 0 }}>
        <StatusBar light />
        <div style={{ padding: '2px 18px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={onBack} style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Icon name="arrow-left" size={21} color="#fff" />
            </button>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: SANS, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{place.name}</div>
              <h1 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 24, color: '#fff', margin: 0, lineHeight: 1.1 }}>Reviews &amp; Stories</h1>
            </div>
          </div>
        </div>
      </div>

      {/* filter chips */}
      <div style={{ flexShrink: 0, background: T.cream, borderBottom: `1px solid ${T.line}` }}>
        <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '13px 22px' }}>
          {filterChips.map((f) => {
            const on = filter === f.id;
            return (
              <button key={f.id} onClick={() => setFilter(f.id)} style={{
                flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6, padding: '9px 15px', borderRadius: 999, cursor: 'pointer',
                border: on ? `1px solid ${T.navy}` : `1px solid ${T.line}`, background: on ? T.navy : T.card,
                fontFamily: SANS, fontWeight: 700, fontSize: 13.5, color: on ? '#fff' : T.body, whiteSpace: 'nowrap', transition: 'all .15s',
              }}>
                <Icon name={f.icon} size={14} color={on ? '#fff' : T.muted} />{f.label}
                <span style={{ fontFamily: SANS, fontSize: 11.5, fontWeight: 700, color: on ? 'rgba(255,255,255,0.6)' : T.muted }}>{counts[f.id] || 0}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* body */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '16px 22px 130px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          {filter === 'all' && (
            <React.Fragment>
              <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 18, padding: 16 }}>
                <RatingSummary data={data} />
              </div>
              <ImpactStrip gamify={gamify} />
              {(data.photos && data.photos.length > 0) && <PhotoWall photos={data.photos} count={`${fmtK(HM.ME.counts.photos * 90 + 40)}`} />}
            </React.Fragment>
          )}

          {/* list header: count + sort */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h2 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 20, color: T.ink, margin: 0 }}>
              {filter === 'all' ? 'All contributions' : HM.CTYPES[filter].label + 's'}
              <span style={{ fontFamily: SANS, fontWeight: 600, fontSize: 14, color: T.muted, marginLeft: 8 }}>{list.length}</span>
            </h2>
            <button onClick={() => setSortOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 13px', borderRadius: 10, cursor: 'pointer', border: `1px solid ${T.line}`, background: T.white, fontFamily: SANS, fontWeight: 700, fontSize: 13, color: T.body }}>
              <Icon name="sort" size={15} color={T.muted} />{SORTS.find((s) => s.id === sort).label}
            </button>
          </div>

          {list.length ? list.map((it) => <ContributionCard key={it.id} item={it} aiLearning={aiLearning} />)
            : <div style={{ textAlign: 'center', padding: '40px 20px' }}>
                <div style={{ width: 60, height: 60, borderRadius: 999, background: T.cream2, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
                  <Icon name={HM.CTYPES[filter] ? HM.CTYPES[filter].icon : 'users'} size={26} color={T.muted} />
                </div>
                <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 19, color: T.ink }}>Be the first</div>
                <div style={{ fontFamily: SANS, fontSize: 14, color: T.muted, marginTop: 4 }}>No {filter} yet — share what you know.</div>
                <button onClick={() => onWrite(filter === 'all' ? null : filter)} style={{ marginTop: 16, padding: '11px 20px', borderRadius: 12, border: 'none', background: T.navy, color: '#fff', cursor: 'pointer', fontFamily: SANS, fontWeight: 700, fontSize: 14 }}>Add {filter === 'all' ? 'a contribution' : 'the first ' + filter}</button>
              </div>}
        </div>
      </div>

      {/* sticky write CTA */}
      <div style={{ flexShrink: 0, padding: '13px 22px 20px', background: T.cream, borderTop: `1px solid ${T.line}` }}>
        <button onClick={() => onWrite(filter === 'all' ? null : filter)} className="gw-press" style={{
          width: '100%', padding: 16, borderRadius: 16, border: 'none', cursor: 'pointer', background: T.navy, color: '#fff',
          fontFamily: SANS, fontWeight: 800, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9,
          boxShadow: '0 10px 24px rgba(16,40,66,0.28)',
        }}>
          <Icon name="edit" size={19} color="#fff" />Write a contribution
        </button>
      </div>

      {/* sort sheet */}
      {sortOpen && (
        <div style={{ position: 'absolute', inset: 0, zIndex: 50, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
          <div onClick={() => setSortOpen(false)} className="gw-back-in" style={{ position: 'absolute', inset: 0, background: 'rgba(8,18,32,0.45)' }} />
          <div className="gw-sheet-in" style={{ position: 'relative', background: T.card, borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: '14px 22px 26px' }}>
            <div style={{ width: 42, height: 5, borderRadius: 999, background: T.line, margin: '0 auto 16px' }} />
            <h3 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 21, color: T.ink, margin: '0 0 12px' }}>Sort by</h3>
            {SORTS.map((s) => (
              <button key={s.id} onClick={() => { setSort(s.id); setSortOpen(false); }} style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 12, padding: '15px 4px', cursor: 'pointer', background: 'none', border: 'none', borderBottom: `1px solid ${T.line}`,
              }}>
                <span style={{ flex: 1, textAlign: 'left', fontFamily: SANS, fontWeight: 600, fontSize: 16, color: T.ink }}>{s.label}</span>
                {sort === s.id && <Icon name="check" size={20} color={T.teal} />}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CommunityScreen, ImpactStrip, PhotoWall });
