/* Collection screen — photo-first grid, featured card, contribution portfolio */

function CollectionScreen({ onCardTap, onTabChange }) {
  const [filter, setFilter] = React.useState('all');

  const cards = [
    { id:'c1', name:'Mori Tea House',   place:'Daikanyama', role:'First Refresh', date:'2026.04.30', seed:'mori-tea-house-daikanyama', rarity:'first-refresh' },
    { id:'c2', name:'Onibus Coffee',    place:'Naka-Meguro', role:'Refresh',      date:'2026.04.28', seed:'onibus-coffee-naka-meguro', rarity:'standard' },
    { id:'c3', name:'Sarugakucho 14-3', place:'Daikanyama', role:'First Mapper',  date:'2026.04.27', seed:'sarugakucho143',            rarity:'hidden-gem' },
    { id:'c4', name:'Cosme Kitchen',    place:'Daikanyama', role:'Verify',        date:'2026.04.25', seed:'cosmekitchen',               rarity:'standard' },
    { id:'c5', name:'Ivy Place',        place:'Daikanyama', role:'Refresh',       date:'2026.04.21', seed:'ivyplace',                  rarity:'standard' },
    { id:'c6', name:'Saturdays NYC',    place:'Daikanyama', role:'Verify',        date:'2026.04.18', seed:'saturdaysnyc',              rarity:'standard' },
  ];

  const filtered = filter === 'all' ? cards
                 : filter === 'rare' ? cards.filter(c => c.rarity !== 'standard')
                 : cards.filter(c => c.place === 'Daikanyama');

  const [featuredCard, ...restCards] = filtered;

  const rarityAccent = (rarity) =>
    rarity === 'first-refresh' ? 'var(--status-rare)'
    : rarity === 'hidden-gem' ? 'var(--status-stale)'
    : 'var(--teal)';

  return (
    <>
      <StatusBar/>
      <div className="scroll">
        <div style={{padding:'4px 20px 12px'}}>
          <div style={{fontSize:26, fontWeight:700, letterSpacing:'-0.025em', lineHeight:1.1, marginBottom:14}}>
            Collection
          </div>

          {/* Stat strip — compact, 3 numbers */}
          <div style={{
            display:'grid', gridTemplateColumns:'1fr 1fr 1fr',
            background:'var(--bg-elev)', border:'1px solid var(--line)', borderRadius:12,
            padding:'12px 0', marginBottom:16,
          }}>
            <StatCol label="POIs" value="84"/>
            <StatCol label="Rare" value="7" border/>
            <StatCol label="Cities" value="3" border/>
          </div>

          {/* Filter chips */}
          <div style={{display:'flex', gap:6, marginBottom:16, overflowX:'auto'}}>
            {[
              {id:'all', label:'All'},
              {id:'rare', label:'Rare'},
              {id:'daika', label:'Daikanyama'},
              {id:'route', label:'Routes'},
              {id:'first', label:'First Mapper'},
            ].map(c => (
              <button key={c.id} onClick={()=>setFilter(c.id)} style={{
                padding:'6px 13px', borderRadius:999,
                border: filter === c.id ? '1px solid var(--ink)' : '1px solid var(--line)',
                background: filter === c.id ? 'var(--ink)' : 'transparent',
                color: filter === c.id ? 'var(--bg)' : 'var(--ink-2)',
                fontFamily:'var(--font-sans)', fontSize:12, fontWeight: filter === c.id ? 600 : 400,
                cursor:'pointer', whiteSpace:'nowrap',
              }}>{c.label}</button>
            ))}
          </div>

          {/* Featured card — first result, full width */}
          {featuredCard && (
            <div style={{marginBottom:12}}>
              <div className="sec-head">
                <h3>{filter === 'all' ? 'Recent contributions' : 'Filtered'}</h3>
                <span className="label">{filtered.length} total</span>
              </div>
              <button onClick={() => onCardTap && onCardTap(featuredCard)} style={{
                width:'100%', background:'transparent', border:0, padding:0, cursor:'pointer', textAlign:'left',
              }}>
                <div style={{
                  position:'relative', height:180, borderRadius:14, overflow:'hidden',
                  border: featuredCard.rarity !== 'standard' ? `1.5px solid ${rarityAccent(featuredCard.rarity)}55` : '1px solid var(--line)',
                  boxShadow:'0 4px 20px -6px rgba(20,32,31,0.12)',
                }}>
                  <img src={poiPhoto(featuredCard.seed, 800, 440)} alt={featuredCard.name}
                    className="photo-cover" style={{position:'absolute', inset:0}}/>
                  <div className="photo-overlay"/>
                  {featuredCard.rarity !== 'standard' && (
                    <div style={{
                      position:'absolute', top:12, left:12,
                      background:'rgba(10,16,16,0.6)', backdropFilter:'blur(6px)',
                      border:'1px solid rgba(255,255,255,0.15)',
                      borderRadius:5, padding:'3px 8px',
                      display:'inline-flex', alignItems:'center', gap:5,
                    }}>
                      <span style={{width:5, height:5, borderRadius:'50%', background:rarityAccent(featuredCard.rarity)}}/>
                      <span style={{fontFamily:'var(--font-mono)', fontSize:8.5, color:'#fff', textTransform:'uppercase', letterSpacing:'0.05em'}}>
                        {featuredCard.role}
                      </span>
                    </div>
                  )}
                  <div style={{position:'absolute', bottom:14, left:14, right:14}}>
                    <div style={{fontSize:19, fontWeight:700, color:'#fff', letterSpacing:'-0.015em', marginBottom:3}}>
                      {featuredCard.name}
                    </div>
                    <div style={{fontSize:12, color:'rgba(255,255,255,0.65)'}}>
                      {featuredCard.place} · {featuredCard.date}
                    </div>
                  </div>
                </div>
              </button>
            </div>
          )}

          {/* Rest of the grid */}
          {restCards.length > 0 && (
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:24}}>
              {restCards.map(c => {
                const accent = rarityAccent(c.rarity);
                return (
                  <button key={c.id} onClick={() => onCardTap && onCardTap(c)} style={{
                    background:'var(--bg-elev)',
                    border: c.rarity !== 'standard' ? `1.5px solid ${accent}44` : '1px solid var(--line)',
                    borderRadius:12, padding:0, cursor:'pointer', textAlign:'left',
                    overflow:'hidden',
                    boxShadow:'0 2px 8px -4px rgba(20,32,31,0.08)',
                  }}>
                    <div style={{
                      height:110, position:'relative', overflow:'hidden', background:'var(--bg-sunk)',
                    }}>
                      <img src={poiPhoto(c.seed, 320, 220)} alt={c.name}
                        className="photo-cover" style={{position:'absolute', inset:0}}/>
                      {/* Small glyph badge */}
                      <div style={{
                        position:'absolute', top:7, left:7,
                        background:'rgba(10,16,16,0.45)', backdropFilter:'blur(6px)',
                        borderRadius:6, padding:2,
                        border:'1px solid rgba(255,255,255,0.1)',
                      }}>
                        <CoordGlyph seed={c.seed} size={22} accent={accent}/>
                      </div>
                      {c.rarity !== 'standard' && (
                        <div style={{
                          position:'absolute', top:7, right:7,
                          width:7, height:7, borderRadius:'50%',
                          background:accent,
                          boxShadow:`0 0 0 2px rgba(255,255,255,0.4)`,
                        }}/>
                      )}
                    </div>
                    <div style={{padding:'9px 10px'}}>
                      <div style={{fontSize:13, fontWeight:600, letterSpacing:'-0.01em',
                        whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>
                        {c.name}
                      </div>
                      <div style={{fontSize:11, color:'var(--ink-3)', marginTop:2}}>
                        {c.role} · {c.date.slice(-5)}
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>
          )}

          {/* Milestones */}
          <div className="sec-head"><h3>Milestones</h3><span className="label">3 of 12</span></div>
          <div style={{display:'flex', flexDirection:'column', gap:8, marginBottom:24}}>
            <Milestone label="100 POIs contributed" progress={84} total={100}/>
            <Milestone label="30-day streak" progress={12} total={30}/>
            <Milestone label="Trusted Verifier · RS 70" progress={64} total={70}/>
          </div>
        </div>
      </div>
      <TabBar active="you" onChange={onTabChange}/>
    </>
  );
}

function StatCol({ label, value, border }) {
  return (
    <div style={{textAlign:'center', borderLeft: border ? '1px solid var(--line)' : 'none'}}>
      <div style={{fontSize:11, color:'var(--ink-3)', fontWeight:500}}>{label}</div>
      <div style={{fontSize:22, fontWeight:700, marginTop:2, fontFamily:'var(--font-mono)', letterSpacing:'-0.02em'}}>
        {value}
      </div>
    </div>
  );
}

function Milestone({ label, progress, total }) {
  const pct = (progress / total) * 100;
  return (
    <div style={{
      background:'var(--bg-elev)', border:'1px solid var(--line)',
      borderRadius:10, padding:'10px 14px',
    }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8}}>
        <div style={{fontSize:13, fontWeight:500}}>{label}</div>
        <div style={{fontSize:12, color:'var(--ink-3)', fontFamily:'var(--font-mono)'}}>{progress}/{total}</div>
      </div>
      <div style={{height:3, background:'var(--bg-sunk)', borderRadius:2, overflow:'hidden'}}>
        <div style={{height:'100%', width:pct+'%', background:'var(--teal)', borderRadius:2}}/>
      </div>
    </div>
  );
}

/* ---- Card detail view ---- */
function CardDetail({ card, cardStyle, onBack, onShare, onMap }) {
  const c = card || {
    name:'Mori Tea House', place:'Daikanyama · Tokyo',
    role:'First Refresh', date:'2026.04.30',
    seed:'mori-tea-house-daikanyama', rarity:'first-refresh',
  };
  return (
    <>
      <StatusBar/>
      <div className="scroll">
        <div style={{padding:'4px 20px 0', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
          <button onClick={onBack} style={{background:'transparent', border:0, padding:0, cursor:'pointer'}}>
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <path d="M14 5 L7 11 L14 17" stroke="var(--ink)" strokeWidth="1.5" strokeLinecap="round"/>
            </svg>
          </button>
          <span className="mono" style={{fontSize:9}}>CARD № 0421</span>
          <div style={{width:22}}/>
        </div>

        <div style={{padding:'24px 20px 0', display:'flex', justifyContent:'center'}}>
          <PoiCard {...c} cardStyle={cardStyle}/>
        </div>

        <div style={{padding:'24px 20px 0'}}>
          <div style={{fontSize:12, fontWeight:600, color:'var(--ink-3)', marginBottom:8, textTransform:'uppercase', letterSpacing:'0.04em', fontFamily:'var(--font-mono)', fontSize:9}}>
            Contribution data
          </div>
          <div style={{
            border:'1px solid var(--line)', borderRadius:10, background:'var(--bg-elev)',
            padding:'4px 14px',
          }}>
            <DetailRow label="POI" value={c.name}/>
            <DetailRow label="Sector" value={c.place}/>
            <DetailRow label="Role" value={c.role}/>
            <DetailRow label="Stamped" value={c.date + ' · 09:43 JST'}/>
            <DetailRow label="Verified by" value="3 contributors"/>
            <DetailRow label="Data used by" value="148 lookups" last/>
          </div>

          <div style={{fontSize:12, fontWeight:500, color:'var(--ink-3)', margin:'20px 0 8px'}}>
            What this unlocked
          </div>
          <div style={{display:'flex', gap:6, flexWrap:'wrap', marginBottom:24}}>
            <Pill tone="teal">+100 GP</Pill>
            <Pill tone="teal">+0.8 RS</Pill>
            <Pill tone="rare">◇ First Refresh</Pill>
            <Pill>Mapper unlocked</Pill>
          </div>
        </div>
      </div>
      <div style={{padding:'12px 20px 24px', borderTop:'1px solid var(--line)', background:'var(--bg-elev)', display:'flex', gap:10}}>
        <button className="btn-secondary" style={{flex:'1 1 40%'}} onClick={() => onMap && onMap(c)}>On Map</button>
        <button className="btn-primary" style={{flex:'1 1 60%'}} onClick={onShare}>Share card</button>
      </div>
    </>
  );
}

function DetailRow({ label, value, last }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'10px 0', borderBottom: last ? 'none' : '1px dashed var(--line)',
    }}>
      <span style={{fontSize:12, color:'var(--ink-3)', fontWeight:500}}>{label}</span>
      <span style={{fontSize:13, fontWeight:500}}>{value}</span>
    </div>
  );
}

/* ---- Share sheet ---- */
function ShareSheet({ card, cardStyle, onClose }) {
  const c = card || {
    name:'Mori Tea House', place:'Daikanyama · Tokyo',
    role:'First Refresh', date:'2026.04.30',
    seed:'mori-tea-house-daikanyama', rarity:'first-refresh',
  };
  const [format, setFormat] = React.useState('square');

  return (
    <div style={{
      position:'absolute', inset:0,
      background:'rgba(10,16,16,0.55)',
      backdropFilter:'blur(6px)',
      display:'flex', flexDirection:'column', justifyContent:'flex-end',
      zIndex:100, animation:'fadein .2s ease',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background:'var(--bg)', borderTopLeftRadius:22, borderTopRightRadius:22,
        padding:'8px 0 24px', maxHeight:'90%', overflow:'auto',
        animation:'slideup .25s ease',
      }}>
        <div style={{display:'flex', justifyContent:'center', padding:'6px 0 14px'}}>
          <div style={{width:36, height:4, borderRadius:2, background:'var(--line-2)'}}/>
        </div>

        <div style={{padding:'0 20px 16px'}}>
          <div style={{fontSize:20, fontWeight:700, letterSpacing:'-0.02em', lineHeight:1.15}}>
            Share this discovery
          </div>
          <div style={{fontSize:13, color:'var(--ink-3)', marginTop:4}}>
            Caption auto-generated from your contribution data.
          </div>
        </div>

        <div style={{
          margin:'0 20px 16px', padding:20,
          background:'var(--bg-sunk)', borderRadius:14,
          display:'flex', justifyContent:'center',
        }}>
          <div style={{transform: format === 'story' ? 'scale(0.6)' : 'scale(0.75)', transformOrigin:'center top'}}>
            <PoiCard {...c} cardStyle={cardStyle}/>
          </div>
        </div>

        <div style={{padding:'0 20px 14px'}}>
          <div style={{fontSize:12, fontWeight:500, color:'var(--ink-3)', marginBottom:8}}>Format</div>
          <div style={{display:'flex', gap:8}}>
            {[
              {id:'square', label:'Square', sub:'1:1 · feed'},
              {id:'story', label:'Story', sub:'9:16 · vertical'},
              {id:'cover', label:'Cover', sub:'16:9 · video'},
            ].map(f => (
              <button key={f.id} onClick={()=>setFormat(f.id)} style={{
                flex:1, padding:'10px 8px', borderRadius:10,
                border: format === f.id ? '1.5px solid var(--ink)' : '1px solid var(--line)',
                background: format === f.id ? 'var(--bg-elev)' : 'transparent',
                cursor:'pointer', textAlign:'left',
              }}>
                <div style={{fontSize:13, fontWeight:600}}>{f.label}</div>
                <div style={{fontSize:11, color:'var(--ink-3)', marginTop:2}}>{f.sub}</div>
              </button>
            ))}
          </div>
        </div>

        <div style={{padding:'8px 20px 14px'}}>
          <div style={{display:'flex', justifyContent:'space-between', marginBottom:8}}>
            <span style={{fontSize:12, fontWeight:500, color:'var(--ink-3)'}}>Caption draft</span>
            <span style={{fontSize:12, color:'var(--teal-ink)', fontWeight:500}}>Edit</span>
          </div>
          <div style={{
            border:'1px solid var(--line)', borderRadius:10,
            padding:'12px 14px', background:'var(--bg-elev)',
            fontSize:13, lineHeight:1.55, color:'var(--ink-2)',
          }}>
            Found a quiet tea spot in Daikanyama — first refresh in 243 days. Worth the detour for the afternoon light.{' '}
            <span style={{color:'var(--teal-ink)'}}>
              #GoVibe #Daikanyama #HiddenGem
            </span>
          </div>
        </div>

        <div style={{padding:'8px 20px 0'}}>
          <div style={{fontSize:12, fontWeight:500, color:'var(--ink-3)', marginBottom:10}}>Share to</div>
          <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:10}}>
            <ShareTarget label="X" bg="#0a0a0a" fg="#fff" glyph="X"/>
            <ShareTarget label="Instagram" bg="linear-gradient(135deg, #f58529, #dd2a7b, #8134af)" fg="#fff" glyph={
              <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                <rect x="3" y="3" width="16" height="16" rx="4.5" stroke="currentColor" strokeWidth="1.6"/>
                <circle cx="11" cy="11" r="4" stroke="currentColor" strokeWidth="1.6"/>
                <circle cx="16" cy="6" r="1" fill="currentColor"/>
              </svg>
            }/>
            <ShareTarget label="Xiaohongshu" bg="#ff2442" fg="#fff" glyph="小"/>
            <ShareTarget label="TikTok" bg="#0a0a0a" fg="#fff" glyph={
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                <path d="M13 3 L13 12 C13 14 11.5 15.5 9.5 15.5 C7.5 15.5 6 14 6 12 C6 10 7.5 8.5 9.5 8.5 L9.5 11 C8.7 11 8 11.7 8 12.5 C8 13.3 8.7 14 9.5 14 C10.3 14 11 13.3 11 12.5 L11 3 Z M13 3 C13 4.5 14 5.7 15.5 6 L15.5 8 C13.7 7.7 12 6.5 12 5"
                  fill="currentColor"/>
              </svg>
            }/>
            <ShareTarget label="Threads" bg="#0a0a0a" fg="#fff" glyph="@"/>
            <ShareTarget label="Facebook" bg="#1877f2" fg="#fff" glyph="f"/>
            <ShareTarget label="Copy link" bg="var(--bg-elev)" fg="var(--ink)" border glyph={
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                <path d="M7 11 L11 7 M5 9 L4 10 C2.5 11.5 2.5 13.5 4 15 C5.5 16.5 7.5 16.5 9 15 L10 14 M13 9 L14 8 C15.5 6.5 15.5 4.5 14 3 C12.5 1.5 10.5 1.5 9 3 L8 4"
                  stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/>
              </svg>
            }/>
            <ShareTarget label="More" bg="var(--bg-elev)" fg="var(--ink)" border glyph="···"/>
          </div>
        </div>

        <div style={{padding:'20px 20px 0', display:'flex', gap:10}}>
          <button className="btn-secondary" style={{flex:'1 1 50%'}} onClick={onClose}>Done</button>
          <button className="btn-primary" style={{flex:'1 1 50%'}}>Save image</button>
        </div>
      </div>
      <style>{`
        @keyframes fadein { from { opacity:0 } to { opacity:1 } }
        @keyframes slideup { from { transform:translateY(40px); opacity:0 } to { transform:translateY(0); opacity:1 } }
      `}</style>
    </div>
  );
}

function ShareTarget({ label, bg, fg, glyph, border }) {
  return (
    <button style={{
      background:'transparent', border:0, padding:0, cursor:'pointer',
      display:'flex', flexDirection:'column', alignItems:'center', gap:6,
    }}>
      <div style={{
        width:48, height:48, borderRadius:12,
        background:bg, color:fg,
        border: border ? '1px solid var(--line)' : 'none',
        display:'flex', alignItems:'center', justifyContent:'center',
        fontSize:18, fontWeight:700, fontFamily:'var(--font-sans)',
      }}>{glyph}</div>
      <span style={{fontSize:10, color:'var(--ink-2)', textAlign:'center', lineHeight:1.2}}>{label}</span>
    </button>
  );
}

Object.assign(window, { CollectionScreen, CardDetail, ShareSheet });
