// sc-screens-home.jsx — V2 Home Dashboard (cross-mode)

function HomeScreen({ viewerId, onOpenGroup, onOpenItem, onOpenHead, onTab, onPeekHere }){
  const s = useStore();
  const me = s.people[viewerId];

  const myGroups = s.groups.filter(g=>g.members.includes(viewerId));
  const heldChat = myGroups.filter(g=>g.holderId===viewerId);
  const ipForMe = inpersonForUser(s, viewerId);
  const heldIp = ipForMe.filter(r=>r.holderId===viewerId);
  const totalCrowns = heldChat.length + heldIp.length;

  // Hot rivalries — pairs with most flips in last 14 days
  const rivalScore = {};
  ipForMe.forEach(r=>{
    rivalScore[r.withId] = (rivalScore[r.withId]||0) + r.transfers.filter(t=>Date.now()-t.at < 14*86400000).length;
  });
  const topRivals = Object.entries(rivalScore).sort((a,b)=>b[1]-a[1]).slice(0,3);

  // Recent mixed activity
  const recent = s.activity.filter(a=>{
    if (a.mode==='chat') return s.groups.find(g=>g.id===a.groupId)?.members.includes(viewerId);
    if (a.mode==='inperson') return a.pairKey.split('::').includes(viewerId);
    return false;
  }).slice(0,5);

  // Pending in chat groups awaiting my vote
  const pendingForMe = [];
  myGroups.forEach(g=>{
    g.pendingSpots.forEach(p=>{
      if (p.byId!==viewerId && !p.votes[viewerId]){
        pendingForMe.push({ g, p });
      }
    });
  });

  return (
    <>
      <NavBar
        title={`Hi, ${me.first}`}
        subtitle={totalCrowns>0
          ? `You're holding ${totalCrowns} crown${totalCrowns===1?'':'s'} right now`
          : `Time to claim something`}
        right={<Ava person={me} size={36} ring/>}
      />
      <ScrollBody>
        {/* Big crown summary */}
        <Card style={{padding:'14px 14px 16px', marginBottom:14, background:'linear-gradient(170deg, #FFFBF0, #FFFDF8)'}}>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
            <div style={{padding:'10px 12px', background:'#fff', borderRadius:14,
              boxShadow:'0 0 0 0.5px var(--hair)'}}>
              <div style={{display:'flex', alignItems:'center', gap:6, color:'var(--muted)', fontSize:11.5, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase'}}>
                <Icon name="people" size={13} color="var(--muted)" stroke={2}/> Group
              </div>
              <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:6}}>
                <div style={{fontSize:30, fontWeight:600, letterSpacing:'-.02em', color:'var(--crown-2)'}}>{heldChat.length}</div>
                <Crown size={16} color="var(--crown)"/>
              </div>
              <div style={{fontSize:12, color:'var(--muted)', marginTop:1}}>of {myGroups.length} groups</div>
            </div>
            <div style={{padding:'10px 12px', background:'#fff', borderRadius:14,
              boxShadow:'0 0 0 0.5px var(--hair)'}}>
              <div style={{display:'flex', alignItems:'center', gap:6, color:'var(--muted)', fontSize:11.5, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase'}}>
                <Icon name="qr" size={13} color="var(--muted)" stroke={2}/> In&nbsp;Person
              </div>
              <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:6}}>
                <div style={{fontSize:30, fontWeight:600, letterSpacing:'-.02em', color:'var(--crown-2)'}}>{heldIp.length}</div>
                <Crown size={16} color="var(--crown)"/>
              </div>
              <div style={{fontSize:12, color:'var(--muted)', marginTop:1}}>of {ipForMe.length} bilaterals</div>
            </div>
          </div>
        </Card>

        {/* Quick "Spot in person" hero */}
        <button onClick={()=>onPeekHere()} className="tap" style={{
          width:'100%', border:'none', marginBottom:18,
          background:'linear-gradient(160deg, var(--crown), var(--crown-2))',
          color:'#fff', borderRadius:18, padding:'16px 18px',
          display:'flex', alignItems:'center', gap:14,
          boxShadow:'0 8px 22px rgba(214,158,61,0.35)',
          textAlign:'left',
        }}>
          <div style={{
            width:46, height:46, borderRadius:14, background:'rgba(255,255,255,0.18)',
            display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <Icon name="qr" size={24} color="#fff" stroke={2.2}/>
          </div>
          <div style={{flex:1}}>
            <div style={{fontSize:16.5, fontWeight:700, letterSpacing:'-.01em'}}>Spot something here</div>
            <div style={{fontSize:13, color:'rgba(255,255,255,0.82)', marginTop:1}}>Show the crown to people nearby</div>
          </div>
          <Icon name="chev" size={20} color="#fff" stroke={2.2}/>
        </button>

        {/* Pending confirmations callout */}
        {pendingForMe.length>0 && (
          <Card style={{padding:'12px 14px', marginBottom:18, background:'#FFF7E6',
            boxShadow:'0 0 0 1px rgba(214,158,61,0.3)'}} onClick={()=>onTab('activity')}>
            <div style={{display:'flex', alignItems:'center', gap:12}}>
              <div style={{
                width:36, height:36, borderRadius:10, background:'var(--crown)',
                display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
              }}>
                <Icon name="bell" size={18} color="#fff" stroke={2.2}/>
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:14.5, fontWeight:600, letterSpacing:'-.01em'}}>
                  {pendingForMe.length} pending claim{pendingForMe.length===1?'':'s'} need{pendingForMe.length===1?'s':''} your vote
                </div>
                <div style={{fontSize:12.5, color:'var(--ink-2)'}}>
                  In {pendingForMe.map(x=>x.g.name).slice(0,2).join(', ')}{pendingForMe.length>2?'…':''}
                </div>
              </div>
              <Icon name="chev" size={16} color="var(--muted)"/>
            </div>
          </Card>
        )}

        {/* Hot rivalries */}
        {topRivals.length>0 && (
          <>
            <SectionHeader title="HOT RIVALRIES" right={<a onClick={()=>onTab('inperson')} style={{color:'var(--crown-2)', fontSize:13, fontWeight:600, cursor:'pointer'}}>See all</a>}/>
            <div style={{display:'flex', gap:10, overflowX:'auto', marginBottom:18, padding:'2px 0 4px',
              scrollbarWidth:'none'}}>
              {topRivals.map(([rid, score])=>{
                const op = s.people[rid];
                const myWins = ipForMe.filter(r=>r.withId===rid && r.holderId===viewerId).length;
                const theirWins = ipForMe.filter(r=>r.withId===rid && r.holderId===rid).length;
                return (
                  <div key={rid} onClick={()=>onOpenHead(rid)} className="tap" style={{
                    minWidth:160, padding:'14px 14px 12px', background:'#fff', borderRadius:16,
                    boxShadow:'0 1px 2px rgba(0,0,0,0.04), 0 0 0 0.5px var(--hair)',
                    display:'flex', flexDirection:'column', gap:10,
                  }}>
                    <div style={{display:'flex', alignItems:'center', gap:8}}>
                      <Ava person={op} size={36}/>
                      <div style={{flex:1, minWidth:0}}>
                        <div style={{fontSize:14, fontWeight:600, letterSpacing:'-.01em', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{op.first}</div>
                        <div style={{fontSize:11, color:'var(--muted)'}}>{score} flips · 14d</div>
                      </div>
                    </div>
                    <div style={{display:'flex', gap:6, alignItems:'center'}}>
                      <Chip tone="crown" style={{flex:1, justifyContent:'center'}}>You {myWins}</Chip>
                      <span style={{fontSize:11, color:'var(--muted)'}}>vs</span>
                      <Chip tone="rival" style={{flex:1, justifyContent:'center'}}>Them {theirWins}</Chip>
                    </div>
                  </div>
                );
              })}
            </div>
          </>
        )}

        {/* Active groups (top 3) */}
        <SectionHeader title="ACTIVE GROUPS" right={<a onClick={()=>onTab('groups')} style={{color:'var(--crown-2)', fontSize:13, fontWeight:600, cursor:'pointer'}}>All groups</a>}/>
        <Card style={{padding:0, overflow:'hidden', marginBottom:18}}>
          {myGroups.slice(0,3).map((g, i, arr)=>{
            const it = s.itemById[g.itemId];
            const isMine = g.holderId===viewerId;
            const holder = g.holderId ? s.people[g.holderId] : null;
            const pending = g.pendingSpots.length;
            return (
              <div key={g.id} onClick={()=>onOpenGroup(g.id)} className="tap" style={{
                padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                borderBottom: i<arr.length-1?'0.5px solid var(--hair)':'none',
              }}>
                <div style={{position:'relative'}}>
                  <ItemTile item={it} size={42} rounded={11}/>
                  {isMine && (
                    <div style={{position:'absolute', top:-4, left:-4, width:20, height:20, borderRadius:'50%',
                      background:'var(--crown)', display:'flex', alignItems:'center', justifyContent:'center',
                      boxShadow:'0 0 0 2px #fff'}}>
                      <Crown size={10} color="#fff"/>
                    </div>
                  )}
                </div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:15, fontWeight:600, letterSpacing:'-.01em'}}>{g.name}</div>
                  <div style={{fontSize:12.5, color:'var(--muted)'}}>
                    {!holder ? 'Vacant' : isMine ? `You · ${fmtHeld(g.heldSince)}` : `${holder.first} · ${fmtHeld(g.heldSince)}`}
                  </div>
                </div>
                {pending>0 && <Chip tone="crown" style={{fontSize:11}}>{pending} pending</Chip>}
                <Icon name="chev" size={16} color="var(--muted)"/>
              </div>
            );
          })}
        </Card>

        {/* Recent activity preview */}
        <SectionHeader title="RECENT" right={<a onClick={()=>onTab('activity')} style={{color:'var(--crown-2)', fontSize:13, fontWeight:600, cursor:'pointer'}}>All activity</a>}/>
        <Card style={{padding:0, overflow:'hidden', marginBottom:18}}>
          {recent.map((a, i)=>{
            const by = s.people[a.byId];
            const item = s.itemById[a.itemId];
            const youDid = a.byId===viewerId;
            const youLost = a.takenFrom===viewerId;
            let label, sub;
            if (a.mode==='chat'){
              label = youDid ? `You claimed in ${a.groupName}` : `${by.first} claimed in ${a.groupName}`;
              sub = a.kind==='pending' ? `Pending · ${Object.values(a.score||{0:0}).reduce ? a.score : 0}/${a.needed}` : (youLost ? 'Took your crown' : 'Crown moved');
            } else {
              const op = s.people[a.withId];
              label = youDid ? `You spotted with ${op.first}` : `${by.first} spotted with you`;
              sub = a.comment ? `"${a.comment.slice(0,40)}${a.comment.length>40?'…':''}"` : 'In person';
            }
            return (
              <div key={a.id} style={{
                padding:'10px 14px', display:'flex', alignItems:'center', gap:12,
                borderBottom: i<recent.length-1?'0.5px solid var(--hair)':'none',
              }}>
                <div style={{position:'relative'}}>
                  <ItemTile item={item} size={36} rounded={10}/>
                  {a.mode==='inperson' && (
                    <div style={{position:'absolute', bottom:-3, right:-3, width:16, height:16, borderRadius:'50%',
                      background:'var(--rival)', display:'flex', alignItems:'center', justifyContent:'center',
                      boxShadow:'0 0 0 1.5px #fff'}}>
                      <Icon name="qr" size={9} color="#fff" stroke={2.6}/>
                    </div>
                  )}
                </div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:14, fontWeight:600, letterSpacing:'-.01em', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{label}</div>
                  <div style={{fontSize:12, color:'var(--muted)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{sub}</div>
                </div>
                <div style={{fontSize:11, color:'var(--muted)', flexShrink:0}}>{fmtDaysAgo(a.at)}</div>
              </div>
            );
          })}
        </Card>

        <div style={{height:8}}/>
      </ScrollBody>
    </>
  );
}

function SectionHeader({ title, right }){
  return (
    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'2px 4px 8px'}}>
      <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em'}}>{title}</div>
      {right}
    </div>
  );
}

// ─── Groups list (lifted from old Home) ─────────────────────────────
function GroupsListScreen({ viewerId, onOpenGroup, onCreate }){
  const s = useStore();
  const myGroups = s.groups.filter(g=>g.members.includes(viewerId));
  return (
    <>
      <NavBar title="Groups" right={
        <button onClick={onCreate} className="tap" style={{
          width:36, height:36, borderRadius:'50%', border:'none', background:'#fff',
          display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow:'0 1px 2px rgba(0,0,0,0.05), 0 0 0 0.5px rgba(0,0,0,0.06)',
        }}>
          <Icon name="plus" size={20} color="var(--ink-2)" stroke={2.2}/>
        </button>
      }/>
      <ScrollBody>
        <Card style={{padding:0, overflow:'hidden'}}>
          {myGroups.map((g, i)=>{
            const it = s.itemById[g.itemId];
            const holder = g.holderId ? s.people[g.holderId] : null;
            const isMine = g.holderId===viewerId;
            const pending = g.pendingSpots.length;
            return (
              <div key={g.id} onClick={()=>onOpenGroup(g.id)} className="tap" style={{
                padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                borderBottom: i<myGroups.length-1?'0.5px solid var(--hair)':'none',
              }}>
                <div style={{position:'relative'}}>
                  <ItemTile item={it} size={44} rounded={11}/>
                  {isMine && (
                    <div style={{position:'absolute', top:-5, left:-5, width:22, height:22, borderRadius:'50%',
                      background:'var(--crown)', display:'flex', alignItems:'center', justifyContent:'center',
                      boxShadow:'0 0 0 2px #fff'}}>
                      <Crown size={11} color="#fff"/>
                    </div>
                  )}
                </div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:15.5, fontWeight:600, letterSpacing:'-.01em'}}>{g.name}</div>
                  <div style={{fontSize:13, color:'var(--muted)'}}>
                    {!holder ? 'Vacant · be first!' : isMine ? 'You hold the crown' : `${holder.first} holds the crown`}
                  </div>
                </div>
                {pending>0 && <Chip tone="crown" style={{fontSize:11}}>{pending}</Chip>}
                <div style={{fontSize:14, fontWeight:600, color:'var(--ink)'}}>{!holder?'—':fmtHeld(g.heldSince)}</div>
                <Icon name="chev" size={16} color="var(--muted)" stroke={2}/>
              </div>
            );
          })}
        </Card>
        <div style={{height:16}}/>
      </ScrollBody>
    </>
  );
}

Object.assign(window, { HomeScreen, GroupsListScreen, SectionHeader });
