// sc-screens-extra.jsx — Create Group, Head-to-Head, Settings, Photo viewer, Invite

// ─── Create Group wizard ───────────────────────────────────────────────
function CreateGroupFlow({ viewerId, onClose, onCreated }){
  const s = useStore();
  const [step, setStep] = React.useState('item'); // item -> customize -> invite -> done
  const [itemId, setItemId] = React.useState(null);
  const [name, setName] = React.useState('');
  const [titleOverride, setTitleOverride] = React.useState('');
  const [region, setRegion] = React.useState('Japan');
  const [members, setMembers] = React.useState(new Set(['ayaka','sam']));
  const [verif, setVerif] = React.useState({ photoRequired:true, photoConfirms:0, photolessConfirms:1 });
  const [createdId, setCreatedId] = React.useState(null);

  const regions = ['Japan','Europe','Worldwide','Original'];
  const filtered = s.items.filter(i=>i.region===region);

  function createIt(){
    const item = s.itemById[itemId];
    const finalName = name.trim() || `${item.name}s`;
    const id = finalName.toLowerCase().replace(/\s+/g,'-')+'-'+Math.floor(Math.random()*999);
    SC.set(st=>{
      const g = {
        id, name:finalName, itemId, titleOverride: titleOverride.trim()||null,
        members:[viewerId, ...members],
        holderId:null, heldSince:null, streak:0,
        verification: verif, spots:[], ownerId:viewerId,
      };
      return {...st, groups:[g, ...st.groups]};
    });
    setCreatedId(id);
    setStep('invite');
  }

  const stepIdx = {item:0, customize:1, invite:2}[step] ?? 0;

  return (
    <div style={{position:'absolute', inset:0, background:'var(--bg)', zIndex:50, display:'flex', flexDirection:'column'}}>
      <div style={{height:STATUS_H}}/>
      <div style={{padding:'6px 16px', height:44, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <button onClick={onClose} className="tap" style={{border:'none', background:'transparent', color:'var(--crown-2)', fontSize:16, padding:4}}>Cancel</button>
        <div style={{fontSize:16, fontWeight:600}}>New Group</div>
        <div style={{width:60}}/>
      </div>

      {/* progress dots */}
      <div style={{display:'flex', gap:6, justifyContent:'center', padding:'4px 0 10px'}}>
        {[0,1,2].map(i=>(
          <div key={i} style={{width:i===stepIdx?22:6, height:6, borderRadius:3,
            background:i<=stepIdx?'var(--crown)':'var(--hair)', transition:'all 220ms ease'}}/>
        ))}
      </div>

      <div style={{flex:1, overflow:'auto', padding:'0 20px 20px'}}>
        {step==='item' && (
          <>
            <div style={{fontSize:26, fontWeight:500, letterSpacing:'-.02em', marginBottom:6}}>
              Pick an item to spot
            </div>
            <div style={{fontSize:13.5, color:'var(--muted)', marginBottom:14}}>
              One item per group. Friends compete to spot it in the wild.
            </div>

            <Seg options={regions.map(r=>({value:r,label:r}))} value={region} onChange={setRegion} style={{marginBottom:14}}/>

            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10}}>
              {filtered.map(it=>(
                <div key={it.id} onClick={()=>setItemId(it.id)} className="tap" style={{
                  borderRadius:14, padding:8, background:'#fff',
                  boxShadow: itemId===it.id ? '0 0 0 2px var(--crown)' : '0 0 0 0.5px rgba(0,0,0,0.05), 0 1px 2px rgba(0,0,0,0.03)',
                  textAlign:'center',
                }}>
                  <div style={{width:'100%', aspectRatio:'1/1', borderRadius:10, backgroundImage:`url("${it.art}")`, backgroundSize:'cover'}}/>
                  <div style={{fontSize:12.5, fontWeight:600, marginTop:6, letterSpacing:'-.01em'}}>{it.name}</div>
                </div>
              ))}
              <div onClick={()=>alert('Custom item flow — prototype stub')} className="tap" style={{
                borderRadius:14, padding:8, background:'#fff', border:'1px dashed var(--hair)',
                textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
                color:'var(--muted)', fontSize:12, aspectRatio:'1/1.25',
              }}>
                <Icon name="plus" size={22} color="var(--muted)"/>
                <div style={{marginTop:4, fontWeight:600}}>Custom</div>
              </div>
            </div>

            <div style={{height:16}}/>
            <Btn disabled={!itemId} onClick={()=>setStep('customize')}>Continue</Btn>
          </>
        )}

        {step==='customize' && (
          <>
            <div style={{fontSize:26, fontWeight:500, letterSpacing:'-.02em', marginBottom:6}}>
              Customize
            </div>
            <div style={{fontSize:13.5, color:'var(--muted)', marginBottom:14}}>
              Name your group and tune the vibe.
            </div>

            <Card style={{padding:14, marginBottom:12}}>
              <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:12}}>
                <ItemTile item={s.itemById[itemId]} size={52} rounded={12}/>
                <div style={{fontSize:15, fontWeight:600}}>{s.itemById[itemId].name}</div>
              </div>

              <Field label="Group name">
                <input value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Nice Cock Club"
                  style={inputStyle}/>
              </Field>
              <div style={{height:10}}/>
              <Field label={`Title override (default "${s.itemById[itemId].title}")`}>
                <input value={titleOverride} onChange={e=>setTitleOverride(e.target.value)}
                  placeholder="e.g. Cockmaster" style={inputStyle}/>
              </Field>
            </Card>

            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>VERIFICATION</div>
            <Card style={{padding:0, overflow:'hidden', marginBottom:12}}>
              <ToggleRow label="Photo required" value={verif.photoRequired} onChange={v=>setVerif(x=>({...x,photoRequired:v}))}/>
              <StepperRow label="Confirmations (with photo)" value={verif.photoConfirms} min={0} max={5}
                onChange={v=>setVerif(x=>({...x,photoConfirms:v}))}/>
              <StepperRow label="Confirmations (no photo)" value={verif.photolessConfirms} min={1} max={5} last
                onChange={v=>setVerif(x=>({...x,photolessConfirms:v}))}/>
            </Card>

            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>INVITE FRIENDS</div>
            <Card style={{padding:0, overflow:'hidden', marginBottom:16}}>
              {['ayaka','sam','kat','luke','mika','jen','taro'].map((pid,i,arr)=>{
                const p = s.people[pid];
                const on = members.has(pid);
                return (
                  <div key={pid} onClick={()=>setMembers(m=>{
                    const n = new Set(m); if(n.has(pid)) n.delete(pid); else n.add(pid); return n;
                  })} className="tap" style={{
                    padding:'10px 14px', display:'flex', alignItems:'center', gap:12,
                    borderBottom: i<arr.length-1?'0.5px solid var(--hair)':'none',
                  }}>
                    <Ava person={p} size={36}/>
                    <div style={{flex:1, fontSize:15, fontWeight:500, letterSpacing:'-.01em'}}>{p.name}</div>
                    <div style={{width:24, height:24, borderRadius:'50%',
                      background: on?'var(--crown)':'transparent',
                      border: on?'2px solid var(--crown)':'2px solid var(--hair)',
                      display:'flex', alignItems:'center', justifyContent:'center',
                    }}>
                      {on && <Icon name="check" size={13} color="#fff" stroke={3}/>}
                    </div>
                  </div>
                );
              })}
            </Card>

            <Btn onClick={createIt}>Create group</Btn>
          </>
        )}

        {step==='invite' && (
          <>
            <div style={{fontSize:26, fontWeight:500, letterSpacing:'-.02em', marginBottom:6}}>
              Your group is live
            </div>
            <div style={{fontSize:13.5, color:'var(--muted)', marginBottom:16}}>
              Share this link to pull more friends in.
            </div>

            <Card style={{padding:20, textAlign:'center', marginBottom:16}}>
              <div style={{width:150, height:150, margin:'0 auto 14px', background:'#fff',
                border:'1px solid var(--hair)', borderRadius:14, display:'flex', alignItems:'center', justifyContent:'center'}}>
                <QRCode value={'spotcrown.app/'+(createdId||'')} size={130}/>
              </div>
              <div style={{fontSize:12, color:'var(--muted)', fontFamily:'ui-monospace, SFMono-Regular, Menlo, monospace'}}>
                spotcrown.app/{createdId?.slice(0,10) || '...'}
              </div>
            </Card>

            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginBottom:10}}>
              <Btn kind="secondary" leading={<Icon name="copy" size={16} color="var(--ink)"/>}>Copy link</Btn>
              <Btn kind="secondary" leading={<Icon name="share" size={16} color="var(--ink)"/>}>Share</Btn>
            </div>
            <Btn onClick={()=>{ onCreated && createdId && onCreated(createdId); onClose(); }}>Open group</Btn>
          </>
        )}
      </div>
    </div>
  );
}

// ─── Reusable pieces ────────────────────────────────────────────────────
const inputStyle = {
  width:'100%', border:'none', outline:'none',
  background:'var(--bg)', borderRadius:10, padding:'12px 14px',
  fontSize:15, color:'var(--ink)', letterSpacing:'-.01em', fontFamily:'inherit',
};
function Field({ label, children }){
  return (
    <div>
      <div style={{fontSize:11.5, fontWeight:600, color:'var(--muted)', letterSpacing:'.06em', marginBottom:6, textTransform:'uppercase'}}>{label}</div>
      {children}
    </div>
  );
}
function ToggleRow({ label, value, onChange, last=false }){
  return (
    <div style={{padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
      borderBottom: last?'none':'0.5px solid var(--hair)'}}>
      <div style={{flex:1, fontSize:15}}>{label}</div>
      <button onClick={()=>onChange(!value)} className="tap" style={{
        width:46, height:28, borderRadius:14, border:'none',
        background: value?'var(--crown)':'var(--hair)',
        position:'relative', cursor:'pointer', transition:'background 200ms',
      }}>
        <div style={{
          position:'absolute', top:2, left: value?20:2,
          width:24, height:24, borderRadius:'50%', background:'#fff',
          boxShadow:'0 1px 2px rgba(0,0,0,0.15)', transition:'left 200ms',
        }}/>
      </button>
    </div>
  );
}
function StepperRow({ label, value, onChange, min=0, max=5, last=false }){
  return (
    <div style={{padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
      borderBottom: last?'none':'0.5px solid var(--hair)'}}>
      <div style={{flex:1, fontSize:15}}>{label}</div>
      <div style={{display:'flex', alignItems:'center', gap:2, background:'var(--chip)', borderRadius:8, padding:2}}>
        <button onClick={()=>onChange(Math.max(min,value-1))} className="tap" style={{width:28, height:26, border:'none', background:'#fff', borderRadius:6, fontSize:16, fontWeight:600}}>−</button>
        <div style={{width:24, textAlign:'center', fontSize:14, fontWeight:600}}>{value}</div>
        <button onClick={()=>onChange(Math.min(max,value+1))} className="tap" style={{width:28, height:26, border:'none', background:'#fff', borderRadius:6, fontSize:16, fontWeight:600}}>+</button>
      </div>
    </div>
  );
}

// Simple pseudo QR code (not a real QR — placeholder grid)
function QRCode({ value='', size=130 }){
  const n = 17;
  const cells = React.useMemo(()=>{
    let h = 0; for (const c of value) h = (h*31 + c.charCodeAt(0)) >>> 0;
    const arr = [];
    for (let i=0;i<n*n;i++){ h = (h*9301 + 49297) >>> 0; arr.push((h>>i%31)&1); }
    return arr;
  }, [value]);
  const cs = size/n;
  return (
    <svg width={size} height={size}>
      <rect width={size} height={size} fill="#fff"/>
      {cells.map((b,i)=> b? <rect key={i} x={(i%n)*cs} y={Math.floor(i/n)*cs} width={cs} height={cs} fill="#1A1815"/>:null)}
      {/* corners */}
      {[[0,0],[n-7,0],[0,n-7]].map(([x,y],k)=>(
        <g key={k}>
          <rect x={x*cs} y={y*cs} width={7*cs} height={7*cs} fill="#1A1815"/>
          <rect x={(x+1)*cs} y={(y+1)*cs} width={5*cs} height={5*cs} fill="#fff"/>
          <rect x={(x+2)*cs} y={(y+2)*cs} width={3*cs} height={3*cs} fill="#1A1815"/>
        </g>
      ))}
    </svg>
  );
}

// ─── Head-to-Head rivalry ──────────────────────────────────────────────
function HeadToHead({ viewerId, opponentId, onBack }){
  const s = useStore();
  const me = s.people[viewerId];
  const op = s.people[opponentId] || s.people.ayaka;
  const [tab, setTab] = React.useState('all'); // 'all' | 'chat' | 'inperson'

  // Chat-mode stats across shared groups
  const shared = s.groups.filter(g=>g.members.includes(viewerId) && g.members.includes(op.id));
  const myClaims = shared.map(g=>({g, mine:g.spots.filter(sp=>sp.byId===viewerId).length, theirs:g.spots.filter(sp=>sp.byId===op.id).length}));
  const chatMine = myClaims.reduce((a,b)=>a+b.mine,0);
  const chatTheirs = myClaims.reduce((a,b)=>a+b.theirs,0);
  const chatStolenByMe = shared.reduce((a,g)=>a+g.spots.filter(sp=>sp.byId===viewerId && sp.takenFrom===op.id).length,0);
  const chatStolenByThem = shared.reduce((a,g)=>a+g.spots.filter(sp=>sp.byId===op.id && sp.takenFrom===viewerId).length,0);

  // In-person bilateral with this person
  const pairKey = SC.pairKey(viewerId, op.id);
  const pair = s.inperson[pairKey];
  const ipItems = pair ? Object.entries(pair.items).map(([itemId, st])=>({ itemId, ...st })) : [];
  const ipMineNow = ipItems.filter(r=>r.holderId===viewerId).length;
  const ipTheirsNow = ipItems.filter(r=>r.holderId===op.id).length;
  const ipStolenByMe = ipItems.reduce((a,r)=>a+r.transfers.filter(t=>t.byId===viewerId && t.takenFrom===op.id).length,0);
  const ipStolenByThem = ipItems.reduce((a,r)=>a+r.transfers.filter(t=>t.byId===op.id && t.takenFrom===viewerId).length,0);

  let heroMine, heroTheirs, heroLabel;
  if (tab==='chat'){ heroMine=chatMine; heroTheirs=chatTheirs; heroLabel='lifetime claims'; }
  else if (tab==='inperson'){ heroMine=ipMineNow; heroTheirs=ipTheirsNow; heroLabel='crowns held'; }
  else { heroMine=chatMine+ipMineNow; heroTheirs=chatTheirs+ipTheirsNow; heroLabel='combined'; }
  const total = heroMine+heroTheirs || 1;
  const pctMine = Math.round(heroMine/total*100);
  const totalMine = heroMine, totalTheirs = heroTheirs;

  return (
    <>
      <NavBar compact title="Head to Head" onBack={onBack}
        right={<button className="tap" style={{border:'none', background:'transparent', padding:6}}>
          <Icon name="share" size={20} color="var(--ink-2)"/>
        </button>}/>
      <ScrollBody>
        <Seg style={{marginBottom:14}}
          options={[
            {value:'all', label:'All'},
            {value:'chat', label:'Groups'},
            {value:'inperson', label:'In Person'},
          ]}
          value={tab} onChange={setTab}/>
        {/* Split-screen hero */}
        <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
          <div style={{display:'flex', alignItems:'stretch', position:'relative', padding:'18px 0 12px'}}>
            <div style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8,
              background:'linear-gradient(135deg, var(--crown-soft) 0%, transparent 100%)', padding:'12px 8px'}}>
              <Ava person={me} size={70} ring/>
              <div style={{fontSize:15, fontWeight:600}}>You</div>
              <div style={{display:'flex',alignItems:'center', gap:5, fontSize:22, fontWeight:700, color:'var(--crown-2)', letterSpacing:'-.02em'}}>
                <Crown size={18} color="var(--crown)"/>{totalMine}
              </div>
            </div>
            <div style={{position:'absolute', top:18, bottom:12, left:'50%', width:1, background:'linear-gradient(180deg, transparent, var(--hair), transparent)'}}/>
            <div style={{fontSize:15, fontWeight:700, color:'var(--muted)', position:'absolute', top:'50%', left:'50%', transform:'translate(-50%,-50%)', background:'#fff', padding:'4px 8px', borderRadius:8, boxShadow:'0 0 0 0.5px var(--hair)'}}>VS</div>
            <div style={{flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:8,
              background:'linear-gradient(225deg, var(--rival-soft) 0%, transparent 100%)', padding:'12px 8px'}}>
              <Ava person={op} size={70}/>
              <div style={{fontSize:15, fontWeight:600}}>{op.first}</div>
              <div style={{display:'flex',alignItems:'center', gap:5, fontSize:22, fontWeight:700, color:'var(--rival)', letterSpacing:'-.02em'}}>
                <Crown size={18} color="var(--rival)"/>{totalTheirs}
              </div>
            </div>
          </div>
          {/* bar */}
          <div style={{padding:'0 16px 16px'}}>
            <div style={{height:10, borderRadius:6, overflow:'hidden', display:'flex', background:'var(--rival)'}}>
              <div style={{width:pctMine+'%', background:'var(--crown)'}}/>
            </div>
            <div style={{display:'flex', justifyContent:'space-between', marginTop:6, fontSize:12, color:'var(--muted)', fontWeight:600}}>
              <span>{pctMine}%</span>
              <span>{100-pctMine}%</span>
            </div>
          </div>
        </Card>

        {(tab==='all' || tab==='chat') && shared.length>0 && (
          <>
            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px',
              display:'flex', alignItems:'center', gap:6}}>
              <Icon name="people" size={13} color="var(--muted)" stroke={2}/> SHARED GROUPS
            </div>
            <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
              {myClaims.map((row,i)=>(
                <div key={row.g.id} style={{
                  padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                  borderBottom: i<myClaims.length-1?'0.5px solid var(--hair)':'none',
                }}>
                  <ItemTile item={s.itemById[row.g.itemId]} size={36} rounded={9}/>
                  <div style={{flex:1, minWidth:0, fontSize:14.5, fontWeight:600, letterSpacing:'-.01em'}}>{row.g.name}</div>
                  <Chip tone="crown" style={{fontSize:13}}>{row.mine} <Crown size={11} color="var(--crown-2)"/></Chip>
                  <Chip tone="rival" style={{fontSize:13}}>{row.theirs} <Crown size={11} color="var(--rival)"/></Chip>
                </div>
              ))}
            </Card>
            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>CROWN THEFTS · GROUPS</div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14}}>
              <Card style={{textAlign:'center', padding:'14px 8px'}}>
                <div style={{fontSize:28, fontWeight:600, color:'var(--crown-2)', letterSpacing:'-.02em'}}>{chatStolenByMe}</div>
                <div style={{fontSize:12, color:'var(--muted)'}}>You took from {op.first}</div>
              </Card>
              <Card style={{textAlign:'center', padding:'14px 8px'}}>
                <div style={{fontSize:28, fontWeight:600, color:'var(--rival)', letterSpacing:'-.02em'}}>{chatStolenByThem}</div>
                <div style={{fontSize:12, color:'var(--muted)'}}>{op.first} took from you</div>
              </Card>
            </div>
          </>
        )}

        {(tab==='all' || tab==='inperson') && ipItems.length>0 && (
          <>
            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px',
              display:'flex', alignItems:'center', gap:6}}>
              <Icon name="qr" size={13} color="var(--muted)" stroke={2}/> IN-PERSON ITEMS
            </div>
            <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
              {ipItems.map((r, i)=>{
                const it = s.itemById[r.itemId];
                const mine = r.holderId===viewerId;
                return (
                  <div key={r.itemId} style={{
                    padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                    borderBottom: i<ipItems.length-1?'0.5px solid var(--hair)':'none',
                  }}>
                    <ItemTile item={it} size={36} rounded={9}/>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:14.5, fontWeight:600, letterSpacing:'-.01em'}}>{it.name}</div>
                      <div style={{fontSize:12, color:'var(--muted)'}}>
                        {mine ? `You hold · ${fmtHeld(r.heldSince)}` : `${op.first} holds · ${fmtHeld(r.heldSince)}`}
                      </div>
                    </div>
                    {r.streak>1 && <Chip tone="crown" style={{fontSize:11}}><Icon name="flame" size={10} color="var(--crown-2)"/>{r.streak}</Chip>}
                    <Crown size={16} color={mine?'var(--crown)':'var(--rival)'}/>
                  </div>
                );
              })}
            </Card>
            <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>CROWN THEFTS · IN-PERSON</div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14}}>
              <Card style={{textAlign:'center', padding:'14px 8px'}}>
                <div style={{fontSize:28, fontWeight:600, color:'var(--crown-2)', letterSpacing:'-.02em'}}>{ipStolenByMe}</div>
                <div style={{fontSize:12, color:'var(--muted)'}}>Stolen from {op.first}</div>
              </Card>
              <Card style={{textAlign:'center', padding:'14px 8px'}}>
                <div style={{fontSize:28, fontWeight:600, color:'var(--rival)', letterSpacing:'-.02em'}}>{ipStolenByThem}</div>
                <div style={{fontSize:12, color:'var(--muted)'}}>{op.first} stole from you</div>
              </Card>
            </div>
          </>
        )}

        <div style={{height:8}}/>
        <Btn kind="secondary" leading={<Icon name="share" size={16} color="var(--ink)"/>}>Share result</Btn>
        <div style={{height:16}}/>
      </ScrollBody>
    </>
  );
}

// ─── Group Settings ────────────────────────────────────────────────────
function GroupSettingsScreen({ groupId, viewerId, onBack }){
  const s = useStore();
  const g = s.groups.find(x=>x.id===groupId);
  if (!g) return null;
  const item = s.itemById[g.itemId];
  const [policy, setPolicy] = React.useState(g.policy);
  const [title, setTitle] = React.useState(g.titleOverride || item.title);
  const HOUR = 3600*1000, MIN = 60*1000;
  const autoHours = Math.round(policy.autoConfirmAfter / HOUR);
  const takeMins = Math.round(policy.takebackWindow / MIN);
  function update(patch){
    const next = {...policy, ...patch};
    setPolicy(next);
    SC.actions.updateGroupPolicy(groupId, patch);
  }
  return (
    <>
      <NavBar compact title="Group settings" onBack={onBack}/>
      <ScrollBody>
        <Card style={{padding:14, marginBottom:14, display:'flex', alignItems:'center', gap:12}}>
          <ItemTile item={item} size={52} rounded={12}/>
          <div style={{flex:1}}>
            <div style={{fontSize:16, fontWeight:600, letterSpacing:'-.01em'}}>{g.name}</div>
            <div style={{fontSize:13, color:'var(--muted)'}}>{g.members.length} members · {item.name}</div>
          </div>
        </Card>

        <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>ITEM</div>
        <Card style={{padding:14, marginBottom:14}}>
          <Field label="Crown holder title">
            <input value={title} onChange={e=>setTitle(e.target.value)} style={inputStyle}/>
          </Field>
          <div style={{fontSize:11.5, color:'var(--muted)', marginTop:8, lineHeight:1.4}}>
            Editing the item's rules will <b style={{color:'var(--ink-2)'}}>fork</b> it into a custom item for this group.
          </div>
        </Card>

        <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>CONFIRMATION POLICY</div>
        <Card style={{padding:0, overflow:'hidden', marginBottom:8}}>
          <ToggleRow label="Photo required" value={policy.photoRequired} onChange={v=>update({photoRequired:v})}/>
          <StepperRow label="Min approvals to confirm" value={policy.minApprovals} min={0} max={5}
            onChange={v=>update({minApprovals:v})}/>
          <StepperRow label="Auto-confirm after (hours)" value={autoHours} min={1} max={72}
            onChange={v=>update({autoConfirmAfter: v*HOUR})}/>
          <StepperRow label="Take-back window (minutes)" value={takeMins} min={0} max={120} last
            onChange={v=>update({takebackWindow: v*MIN})}/>
        </Card>
        <div style={{fontSize:11.5, color:'var(--muted)', padding:'0 6px 14px', lineHeight:1.45}}>
          Pending spots auto-confirm after {autoHours}h if their net score is non-negative. Admins can confirm instantly.
        </div>

        <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>MEMBERS</div>
        <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
          {g.members.map((mid, i)=>{
            const p = s.people[mid];
            const isAdmin = g.adminIds.includes(mid);
            return (
              <div key={mid} style={{
                padding:'10px 14px', display:'flex', alignItems:'center', gap:8,
                borderBottom: i<g.members.length-1?'0.5px solid var(--hair)':'none',
              }}>
                <Ava person={p} size={34} ring={mid===g.holderId}/>
                <div style={{flex:1, fontSize:15, fontWeight:500}}>{p.name}</div>
                {mid===g.ownerId && <Chip>Owner</Chip>}
                {isAdmin && mid!==g.ownerId && <Chip tone="rival">Admin</Chip>}
                {mid===g.holderId && <Chip tone="crown"><Crown size={11} color="var(--crown-2)"/>Holder</Chip>}
              </div>
            );
          })}
        </Card>

        <Btn kind="secondary" leading={<Icon name="plus" size={16} color="var(--ink)"/>}>Invite more</Btn>
        <div style={{height:10}}/>
        <Btn kind="danger">Leave group</Btn>
        <div style={{height:16}}/>
      </ScrollBody>
    </>
  );
}

// ─── Photo viewer ──────────────────────────────────────────────────────
function PhotoViewer({ spot, group, onClose }){
  const s = useStore();
  const by = s.people[spot.byId];
  const item = s.itemById[group.itemId];
  const from = spot.takenFrom ? s.people[spot.takenFrom] : null;
  return (
    <div style={{position:'absolute', inset:0, zIndex:70, background:'#000', display:'flex', flexDirection:'column', color:'#fff'}}>
      <div style={{height:STATUS_H}}/>
      <div style={{padding:'6px 16px', height:44, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <button onClick={onClose} className="tap" style={{border:'none', background:'rgba(255,255,255,0.12)', width:36, height:36, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <Icon name="x" size={18} color="#fff"/>
        </button>
        <div style={{fontSize:15, fontWeight:600}}>{group.name}</div>
        <button className="tap" style={{border:'none', background:'rgba(255,255,255,0.12)', width:36, height:36, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center'}}>
          <Icon name="share" size={16} color="#fff"/>
        </button>
      </div>
      <PhotoBG emoji={item.emoji} seed={spot.photoSeed} style={{ flex:1, margin:'4px 14px', borderRadius:18, overflow:'hidden',
         }}/>
      <div style={{padding:'16px 20px 40px'}}>
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <Ava person={by} size={40} ring/>
          <div style={{flex:1}}>
            <div style={{fontSize:16, fontWeight:600, letterSpacing:'-.01em'}}>{by.name}</div>
            <div style={{fontSize:13, color:'rgba(255,255,255,0.65)'}}>
              {fmtDaysAgo(spot.at)}{from?` · took from ${from.first}`:''}
            </div>
          </div>
          <Crown size={22} color="var(--crown)"/>
        </div>
      </div>
    </div>
  );
}

// ─── App Settings ──────────────────────────────────────────────────────
function AppSettingsScreen({ viewerId, onBack }){
  const s = useStore();
  const me = s.people[viewerId];
  return (
    <>
      <NavBar compact title="Settings" onBack={onBack}/>
      <ScrollBody>
        <Card style={{padding:14, marginBottom:14, display:'flex', alignItems:'center', gap:12}}>
          <Ava person={me} size={48} ring/>
          <div style={{flex:1}}>
            <div style={{fontSize:16, fontWeight:600, letterSpacing:'-.01em'}}>{me.name}</div>
            <div style={{fontSize:13, color:'var(--muted)'}}>Signed in with Apple</div>
          </div>
          <Icon name="chev" size={16} color="var(--muted)"/>
        </Card>

        <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>NOTIFICATIONS</div>
        <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
          <ToggleRow label="Crown stolen" value={true} onChange={()=>{}}/>
          <ToggleRow label="Crown claimed (group)" value={true} onChange={()=>{}}/>
          <ToggleRow label="Confirmations pending" value={true} onChange={()=>{}} last/>
        </Card>

        <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'0 4px 8px'}}>GENERAL</div>
        <Card style={{padding:0, overflow:'hidden', marginBottom:14}}>
          {[
            {l:'Language', v:'English'},
            {l:'Appearance', v:'System'},
            {l:'About', v:'1.0'},
            {l:'Privacy & data', v:''},
          ].map((r,i,arr)=>(
            <div key={r.l} style={{padding:'14px 14px', display:'flex', alignItems:'center', gap:12,
              borderBottom: i<arr.length-1?'0.5px solid var(--hair)':'none'}}>
              <div style={{flex:1, fontSize:15}}>{r.l}</div>
              <div style={{fontSize:14, color:'var(--muted)'}}>{r.v}</div>
              <Icon name="chev" size={14} color="var(--muted)"/>
            </div>
          ))}
        </Card>

        <Btn kind="danger">Sign out</Btn>
        <div style={{height:16}}/>
      </ScrollBody>
    </>
  );
}

// ─── Friends tab (lightweight) ─────────────────────────────────────────
function FriendsScreen({ viewerId, onOpenHead }){
  const s = useStore();
  const me = s.people[viewerId];
  // Derive people from your groups (excluding you)
  const ids = new Set();
  s.groups.forEach(g=>{ if(g.members.includes(viewerId)) g.members.forEach(m=>m!==viewerId && ids.add(m)); });
  const people = [...ids].map(id=>s.people[id]).filter(Boolean);
  return (
    <>
      <NavBar title="Friends"/>
      <ScrollBody>
        <Card style={{padding:0, overflow:'hidden'}}>
          {people.map((p,i)=>{
            const shared = s.groups.filter(g=>g.members.includes(viewerId) && g.members.includes(p.id));
            const heldByThem = shared.filter(g=>g.holderId===p.id).length;
            return (
              <div key={p.id} onClick={()=>onOpenHead(p.id)} className="tap" style={{
                padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                borderBottom: i<people.length-1?'0.5px solid var(--hair)':'none',
              }}>
                <Ava person={p} size={42}/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:15, fontWeight:600, letterSpacing:'-.01em'}}>{p.name}</div>
                  <div style={{fontSize:12.5, color:'var(--muted)'}}>
                    {shared.length} shared group{shared.length===1?'':'s'} · holds {heldByThem} crown{heldByThem===1?'':'s'}
                  </div>
                </div>
                {heldByThem>0 && <Chip tone="crown"><Crown size={11} color="var(--crown-2)"/>{heldByThem}</Chip>}
                <Icon name="chev" size={16} color="var(--muted)"/>
              </div>
            );
          })}
        </Card>
        <div style={{height:16}}/>
      </ScrollBody>
    </>
  );
}

Object.assign(window, {
  CreateGroupFlow, HeadToHead, GroupSettingsScreen, PhotoViewer,
  AppSettingsScreen, FriendsScreen, Field, ToggleRow, StepperRow, QRCode, inputStyle,
});
