// Feed — chronological stream of everything added to the group

function FeedItem({ item, members, onOpen, onToggleDown, isDown }) {
  const byId = (id) => members.find(m => m.id === id) || { id, name: '?', avatar: '?', color: C.inkMuted };
  const user = byId(item.addedBy);
  const cat = catById(item.category);
  const downUsers = item.downs.map(byId);

  return (
    <div onClick={() => onOpen(item.id)} style={{
      background: C.white,
      borderRadius: 22,
      margin: '0 16px 14px',
      overflow: 'hidden',
      boxShadow: '0 1px 3px rgba(30,42,74,0.04), 0 6px 16px rgba(30,42,74,0.05)',
      cursor: 'pointer',
    }}>
      {/* header: who added it + when */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '14px 16px 10px',
      }}>
        <Avatar user={user} size={30}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: '"DM Sans", system-ui',
            fontSize: 13.5, color: C.navy, letterSpacing: -0.1,
          }}>
            <b style={{ fontWeight: 600 }}>{user.name}</b>
            <span style={{ color: C.inkMuted, fontWeight: 400 }}> shared a{item.type === 'event' ? 'n event' : ' spot'}</span>
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            fontFamily: '"DM Sans", system-ui',
            fontSize: 11.5, color: C.inkMuted, marginTop: 1,
          }}>
            <SourceDot source={item.source}/>
            <span>{item.source === 'Manual' ? 'manual entry' : item.source}</span>
            <span style={{ opacity: 0.5 }}>·</span>
            <span>{item.addedAt}</span>
          </div>
        </div>
      </div>

      {/* Date ribbon for events. Multi-day items show a range pill
          summarizing both endpoints instead of the single-day block. */}
      {item.type === 'event' && item.date && (
        item.endDate ? (
          <div style={{
            margin: '0 16px 10px',
            padding: '10px 14px',
            borderRadius: 14,
            background: C.coralSoft,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
              fontSize: 20, color: C.navy, letterSpacing: -0.3,
              flex: 1,
            }}>
              {dateRangeLabel ? dateRangeLabel(item.date, item.endDate) : `${item.date} → ${item.endDate}`}
            </div>
            <div style={{
              background: '#fff', borderRadius: 999,
              padding: '4px 10px',
              fontFamily: '"DM Sans",system-ui', fontSize: 11.5, fontWeight: 700,
              color: C.coralDeep,
            }}>
              {daysBetween ? daysBetween(item.date, item.endDate) : 2} days
            </div>
          </div>
        ) : (
          <div style={{
            margin: '0 16px 10px',
            padding: '10px 14px',
            borderRadius: 14,
            background: C.coralSoft,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 40, textAlign: 'center',
              fontFamily: '"DM Sans", system-ui',
              color: C.navy,
            }}>
              <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: 0.8, opacity: 0.7 }}>
                {item.date.split(',')[0].toUpperCase()}
              </div>
              <div style={{
                fontFamily: '"Instrument Serif", serif',
                fontSize: 24, lineHeight: 1,
                fontStyle: 'italic',
              }}>
                {item.date.split(' ').pop()}
              </div>
            </div>
            <div style={{ width: 1, height: 32, background: 'rgba(30,42,74,0.18)' }}/>
            <div style={{ fontFamily: '"DM Sans", system-ui', fontSize: 13, color: C.navy, lineHeight: 1.35 }}>
              {item.time && <div style={{ fontWeight: 600 }}>{item.time}</div>}
              {item.location && <div style={{ opacity: 0.65 }}>{item.location}</div>}
            </div>
          </div>
        )
      )}

      {/* image */}
      <div style={{ position: 'relative', margin: '0 16px' }}>
        <Placeholder spec={item.image} radius={16} style={{ width: '100%', aspectRatio: '16 / 10' }}/>
        <div style={{ position: 'absolute', top: 10, left: 10 }}>
          <CategoryBadge cat={cat}/>
        </div>
      </div>

      {/* title + note */}
      <div style={{ padding: '12px 16px 4px' }}>
        <div style={{
          fontFamily: '"DM Sans", system-ui',
          fontWeight: 600, fontSize: 17, color: C.navy,
          letterSpacing: -0.3, lineHeight: 1.25,
        }}>{item.title}</div>
        {item.note && (
          <div style={{
            fontFamily: '"DM Sans", system-ui',
            fontSize: 14, color: C.inkMuted, marginTop: 4,
            lineHeight: 1.4, letterSpacing: -0.1,
          }}>{item.note}</div>
        )}
      </div>

      {/* footer actions */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '12px 16px 14px',
      }}>
        <ImDownPill
          isDown={isDown}
          count={item.downs.length}
          onToggle={() => onToggleDown(item.id)}
        />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, color: C.inkMuted }}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M2 7c0-2.2 2.2-4 5-4.5 3.3-.6 6 1 6.5 3.5.5 2-1 4-3.5 5l-4 2v-2.5C3 9.7 2 8.5 2 7z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
            </svg>
            <span style={{ fontFamily: '"DM Sans",system-ui', fontSize: 13, fontWeight: 500 }}>
              {item.comments}
            </span>
          </div>
          <svg width="17" height="17" viewBox="0 0 17 17" fill="none" style={{ color: C.inkMuted }}>
            <path d="M4 2.5v12l4.5-3 4.5 3v-12z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

// Buckets items by `addedAt` (e.g. "2h", "1d", "5d", "just now") so the
// Today / This week / Earlier groups reflect real post times rather than
// fixed slices. Unparseable values fall through to "Earlier".
function bucketItems(items) {
  const today = [], week = [], earlier = [];
  for (const it of items) {
    const s = String(it.addedAt || '');
    const m = s.match(/^(\d+)\s*([hm]|min)/i);
    const daysM = s.match(/^(\d+)\s*d/i);
    if (/just now|now/i.test(s) || m) {
      today.push(it);
    } else if (daysM) {
      const n = parseInt(daysM[1], 10);
      (n <= 1 ? today : (n <= 7 ? week : earlier)).push(it);
    } else {
      earlier.push(it);
    }
  }
  return [
    { label: 'Today',     items: today },
    { label: 'This week', items: week },
    { label: 'Earlier',   items: earlier },
  ].filter(g => g.items.length);
}

function FeedScreen({ items, userId, huddle, onOpen, onAdd, onToggleDown }) {
  const groups = bucketItems(items);
  const members = huddle?.members || [];
  return (
    <Screen>
      <GroupBar group={huddle} members={huddle.members}/>
      <HuddleHeader title="Feed" subtitle="latest in the group" onAdd={onAdd}/>
      {groups.length === 0 && (
        <div style={{ padding: '0 16px' }}>
          <div style={{
            background: C.white, borderRadius: 18, padding: 22,
            textAlign: 'center',
            boxShadow: '0 1px 3px rgba(30,42,74,0.04)',
          }}>
            <div style={{
              fontFamily: '"Instrument Serif",serif', fontStyle: 'italic',
              fontSize: 22, color: C.navy,
            }}>nothing here yet</div>
            <div style={{
              fontFamily: '"DM Sans",system-ui', fontSize: 13.5, color: C.inkMuted,
              marginTop: 6, lineHeight: 1.45,
            }}>Tap the coral + to paste a link or drop a screenshot.</div>
          </div>
        </div>
      )}
      {groups.map(g => (
        <div key={g.label}>
          <div style={{
            padding: '6px 28px 10px',
            fontFamily: '"DM Sans", system-ui',
            fontSize: 11.5, fontWeight: 700,
            color: C.inkMuted,
            letterSpacing: 1.2,
            textTransform: 'uppercase',
          }}>{g.label}</div>
          {g.items.map(it => (
            <FeedItem
              key={it.id} item={it} members={members}
              isDown={it.downs.includes(userId)}
              onOpen={onOpen}
              onToggleDown={onToggleDown}
            />
          ))}
        </div>
      ))}
    </Screen>
  );
}

Object.assign(window, { FeedScreen });
