// sc-screens-spot.jsx — Spot flow (camera → review → groups → celebration)

function SpotFlow({ viewerId, onClose, initialItemId=null }){
  const s = useStore();
  // steps: 'camera' -> 'review' -> 'groups' -> 'success'
  const [step, setStep] = React.useState('camera');
  const [photoSeed, setPhotoSeed] = React.useState(null);
  const [itemId, setItemId] = React.useState(initialItemId || 'rooster');
  const [selectedGroups, setSelectedGroups] = React.useState(new Set());
  const [cameraMode, setCameraMode] = React.useState('quick'); // manual/quick/series
  const [comment, setComment] = React.useState('');
  const [seriesShots, setSeriesShots] = React.useState([]); // for series mode

  // All groups viewer is in
  const myGroups = s.groups.filter(g=>g.members.includes(viewerId));
  // Groups that match itemId — pre-checked
  const matching = myGroups.filter(g=>g.itemId===itemId);
  const others   = myGroups.filter(g=>g.itemId!==itemId);

  React.useEffect(()=>{
    if (step==='groups'){
      setSelectedGroups(new Set(matching.map(g=>g.id)));
    }
  }, [step, itemId]);

  function capture(){
    setPhotoSeed('snap-'+Date.now());
    setStep('review');
  }
  function proceed(){ setStep('groups'); }
  function claim(){
    const ids = [...selectedGroups];
    if (ids.length>0) SC.actions.spotChat(viewerId, itemId, ids, photoSeed, comment);
    setStep('success');
    setTimeout(()=>{ onClose(); }, 2200);
  }

  // ──────── Camera step ────────
  if (step==='camera'){
    const item = s.itemById[itemId];
    return (
      <div style={{position:'absolute', inset:0, background:'#000', zIndex:50, display:'flex', flexDirection:'column', color:'#fff'}}>
        {/* status bar area */}
        <div style={{height:STATUS_H}}/>
        <div style={{display:'flex', alignItems:'center', padding:'6px 16px', height:44, justifyContent:'space-between'}}>
          <button onClick={onClose} className="tap" style={{border:'none', background:'transparent', color:'#fff', fontSize:16, padding:4}}>Cancel</button>
          <div style={{fontSize:16, fontWeight:600}}>Spot Something</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="flash" size={18} color="#fff"/>
          </button>
        </div>

        {/* Camera viewfinder */}
        <PhotoBG emoji={item.emoji} seed={'view'+itemId}
          style={{flex:1, margin:'6px 14px 0', borderRadius:18, overflow:'hidden', position:'relative', fontSize:120}}>
          {/* targeting corners */}
          {['tl','tr','bl','br'].map(p=>{
            const [v,h] = p.split('');
            return <div key={p} style={{
              position:'absolute', [v==='t'?'top':'bottom']:40, [h==='l'?'left':'right']:40,
              width:38, height:38,
              borderTop: v==='t'?'3px solid #fff':'none',
              borderBottom: v==='b'?'3px solid #fff':'none',
              borderLeft: h==='l'?'3px solid #fff':'none',
              borderRight: h==='r'?'3px solid #fff':'none',
            }}/>;
          })}
          {/* targeting pill */}
          <div style={{position:'absolute', top:22, left:22, right:22, padding:'10px 12px',
            background:'rgba(0,0,0,0.55)', backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)',
            borderRadius:12, display:'flex', alignItems:'center', gap:8}}>
            <div style={{width:20, height:20, borderRadius:'50%', border:'2px solid var(--crown)',
              display:'flex', alignItems:'center', justifyContent:'center'}}>
              <div style={{width:4, height:4, borderRadius:'50%', background:'var(--crown)'}}/>
            </div>
            <div style={{fontSize:13.5, fontWeight:500, letterSpacing:'-.01em'}}>
              Aim at the <b style={{fontWeight:700}}>{item.name.toLowerCase()}</b> and tap to capture
            </div>
          </div>
        </PhotoBG>

        {/* Mode selector */}
        <div style={{display:'flex', justifyContent:'center', gap:26, padding:'14px 0 8px', fontSize:13}}>
          {['manual','quick','series'].map(m=>(
            <button key={m} onClick={()=>setCameraMode(m)} className="tap" style={{
              border:'none', background:'transparent', color: cameraMode===m?'var(--crown)':'rgba(255,255,255,0.6)',
              fontWeight: cameraMode===m?700:500, letterSpacing:'-.01em',
              padding:'4px 2px', textTransform: cameraMode===m?'none':'none',
            }}>
              {m==='manual'?'Manual':m==='quick'?'Quick Spot':'Series'}
            </button>
          ))}
        </div>

        {/* Shutter */}
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'8px 30px 10px'}}>
          <PhotoBG emoji={item.emoji} seed={'thumb'} style={{ width:44, height:44, borderRadius:10, overflow:'hidden', border:'2px solid rgba(255,255,255,0.5)', fontSize:18 }}/>
          <button onClick={capture} className="tap" style={{
            width:68, height:68, borderRadius:'50%', border:'3px solid #fff',
            background:'var(--crown)', cursor:'pointer', boxShadow:'0 0 0 4px rgba(255,255,255,0.15)',
          }}/>
          <button className="tap" style={{width:40, height:40, borderRadius:'50%', border:'none', background:'rgba(255,255,255,0.12)', display:'flex', alignItems:'center', justifyContent:'center'}}>
            <Icon name="flip" size={18} color="#fff"/>
          </button>
        </div>
        <div style={{height:34}}/>
      </div>
    );
  }

  // ──────── Review step (choose/confirm item) ────────
  if (step==='review'){
    const item = s.itemById[itemId];
    return (
      <div style={{position:'absolute', inset:0, background:'var(--bg)', zIndex:50, display:'flex', flexDirection:'column'}}>
        <div style={{height:STATUS_H}}/>
        <NavBar compact title="Confirm the spot" onBack={()=>setStep('camera')}/>
        <div style={{flex:1, overflow:'auto', padding:'0 20px 20px'}}>
          <Card style={{padding:16, textAlign:'center', marginBottom:14}}>
            <PhotoBG emoji={item.emoji} seed={photoSeed} style={{
              width:'100%', aspectRatio:'4/3', borderRadius:14, margin:'0 auto',
              position:'relative', fontSize:80,
            }}>
              <div style={{position:'absolute', bottom:10, right:10, width:34, height:34, borderRadius:'50%',
                background:'var(--ok)', display:'flex', alignItems:'center', justifyContent:'center',
                boxShadow:'0 0 0 3px #fff',
              }}>
                <Icon name="check" size={18} color="#fff" stroke={2.6}/>
              </div>
            </PhotoBG>
            <div style={{fontSize:12, color:'var(--muted)', marginTop:10, letterSpacing:'.06em', fontWeight:600}}>YOUR NEW SPOT</div>
          </Card>

          <div style={{fontSize:24, fontWeight:500, letterSpacing:'-.02em', textAlign:'center', marginBottom:4}}>
            What did you spot?
          </div>
          <div style={{fontSize:13.5, color:'var(--muted)', textAlign:'center', marginBottom:14}}>
            We'll apply it to every matching group.
          </div>

          <Card style={{padding:0, overflow:'hidden', marginBottom:16}}>
            {s.items.slice(0,6).map((it, i)=>(
              <div key={it.id} onClick={()=>setItemId(it.id)} className="tap" style={{
                padding:'10px 14px', display:'flex', alignItems:'center', gap:12,
                borderBottom: i<5?'0.5px solid var(--hair)':'none',
              }}>
                <ItemTile item={it} size={36} rounded={10}/>
                <div style={{flex:1}}>
                  <div style={{fontSize:15, fontWeight:600, letterSpacing:'-.01em'}}>{it.name}</div>
                  <div style={{fontSize:12, color:'var(--muted)'}}>{it.region}</div>
                </div>
                <div style={{width:22, height:22, borderRadius:'50%', border:'2px solid var(--hair)',
                  background: itemId===it.id?'var(--crown)':'transparent',
                  borderColor: itemId===it.id?'var(--crown)':'var(--hair)',
                  display:'flex', alignItems:'center', justifyContent:'center',
                }}>
                  {itemId===it.id && <Icon name="check" size={12} color="#fff" stroke={3}/>}
                </div>
              </div>
            ))}
          </Card>

          <div style={{fontSize:11.5, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', marginBottom:6, textTransform:'uppercase'}}>
            Add a comment (optional)
          </div>
          <Card style={{padding:0, marginBottom:16, overflow:'hidden'}}>
            <textarea value={comment} onChange={e=>setComment(e.target.value)}
              placeholder="Where, when, anything funny…"
              style={{
                width:'100%', minHeight:64, border:'none', outline:'none',
                background:'transparent', padding:'12px 14px',
                fontSize:14.5, fontFamily:'inherit', color:'var(--ink)', resize:'none',
              }}/>
          </Card>

          <Btn onClick={proceed} leading={<Crown size={16} color="#fff"/>}>Continue</Btn>
          <div style={{height:10}}/>
          <Btn kind="ghost" onClick={onClose}>Skip — just save photo</Btn>
        </div>
      </div>
    );
  }

  // ──────── Groups picker ────────
  if (step==='groups'){
    const item = s.itemById[itemId];
    const toggle = gid => setSelectedGroups(prev=>{
      const n = new Set(prev);
      if (n.has(gid)) n.delete(gid); else n.add(gid);
      return n;
    });
    return (
      <div style={{position:'absolute', inset:0, background:'var(--bg)', zIndex:50, display:'flex', flexDirection:'column'}}>
        <div style={{height:STATUS_H}}/>
        <NavBar compact title="Pick groups" onBack={()=>setStep('review')}/>
        <div style={{flex:1, overflow:'auto', padding:'0 20px 20px'}}>
          {/* mini photo header */}
          <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:14}}>
            <PhotoBG emoji={item.emoji} seed={photoSeed} style={{
              width:56, height:56, borderRadius:14, position:'relative', fontSize:28,
            }}>
              <div style={{position:'absolute', bottom:-4, right:-4, width:22, height:22, borderRadius:'50%',
                background:'var(--ok)', display:'flex', alignItems:'center', justifyContent:'center',
                boxShadow:'0 0 0 2px var(--bg)',
              }}>
                <Icon name="check" size={12} color="#fff" stroke={3}/>
              </div>
            </PhotoBG>
            <div style={{flex:1}}>
              <div style={{fontSize:20, fontWeight:500, letterSpacing:'-.02em'}}>
                Claim {selectedGroups.size} crown{selectedGroups.size===1?'':'s'}
              </div>
              <div style={{fontSize:13, color:'var(--muted)'}}>You hold the crown from now on.</div>
            </div>
          </div>

          {matching.length>0 && (
            <>
              <div style={{fontSize:12, fontWeight:600, color:'var(--crown-2)', letterSpacing:'.08em', padding:'2px 4px 8px', display:'flex', alignItems:'center', gap:6}}>
                <Icon name="check" size={13} color="var(--crown-2)" stroke={2.6}/> MATCHING GROUPS
              </div>
              <Card style={{padding:0, overflow:'hidden', marginBottom:16}}>
                {matching.map((g, i)=>{
                  const holder = g.holderId ? s.people[g.holderId] : null;
                  const sel = selectedGroups.has(g.id);
                  return (
                    <div key={g.id} onClick={()=>toggle(g.id)} className="tap" style={{
                      padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                      borderBottom: i<matching.length-1?'0.5px solid var(--hair)':'none',
                    }}>
                      <ItemTile item={s.itemById[g.itemId]} size={40} rounded={11}/>
                      <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 ? (holder.id===viewerId?'Currently held by you':`Currently held by ${holder.first}`) : 'Crown is vacant'}
                        </div>
                      </div>
                      {holder && <Ava person={holder} size={24}/>}
                      <div style={{width:24, height:24, borderRadius:'50%',
                        background: sel?'var(--crown)':'transparent',
                        border: sel?'2px solid var(--crown)':'2px solid var(--hair)',
                        display:'flex', alignItems:'center', justifyContent:'center',
                      }}>
                        {sel && <Icon name="check" size={13} color="#fff" stroke={3}/>}
                      </div>
                    </div>
                  );
                })}
              </Card>
            </>
          )}

          {others.length>0 && (
            <>
              <div style={{fontSize:12, fontWeight:600, color:'var(--muted)', letterSpacing:'.08em', padding:'2px 4px 8px'}}>OTHER GROUPS</div>
              <Card style={{padding:0, overflow:'hidden', marginBottom:18, opacity:.7}}>
                {others.map((g, i)=>(
                  <div key={g.id} style={{
                    padding:'12px 14px', display:'flex', alignItems:'center', gap:12,
                    borderBottom: i<others.length-1?'0.5px solid var(--hair)':'none',
                  }}>
                    <ItemTile item={s.itemById[g.itemId]} size={40} rounded={11}/>
                    <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)'}}>Doesn't match — {s.itemById[g.itemId].name.toLowerCase()}</div>
                    </div>
                    <div style={{width:24, height:24, borderRadius:'50%', border:'2px solid var(--hair)'}}/>
                  </div>
                ))}
              </Card>
            </>
          )}

          <Btn onClick={claim} disabled={selectedGroups.size===0}
            leading={<Crown size={18} color="#fff"/>}>
            Claim {selectedGroups.size} crown{selectedGroups.size===1?'':'s'}
          </Btn>
          <div style={{height:10}}/>
          <Btn kind="ghost" onClick={onClose}>Skip — just save photo</Btn>
        </div>
      </div>
    );
  }

  // ──────── Success ────────
  if (step==='success'){
    const claimed = [...selectedGroups].map(id=>s.groups.find(g=>g.id===id)).filter(Boolean);
    return (
      <div style={{position:'absolute', inset:0, background:'linear-gradient(180deg, #1A1815 0%, #2C2620 100%)', zIndex:60,
        display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', color:'#fff', padding:'40px 20px'}}>
        <div style={{transform:'scale(1)', animation:'crownPop 500ms cubic-bezier(.2,.9,.3,1.4) both'}}>
          <div style={{
            width:140, height:140, borderRadius:'50%',
            background:'radial-gradient(circle at 50% 40%, var(--crown-soft), var(--crown) 70%, var(--crown-2))',
            display:'flex', alignItems:'center', justifyContent:'center',
            boxShadow:'0 20px 60px rgba(214,158,61,0.55)',
          }}>
            <Crown size={72} color="#fff"/>
          </div>
        </div>
        <div style={{fontSize:32, fontWeight:500, letterSpacing:'-.02em', marginTop:28, textAlign:'center'}}>
          Crown claimed!
        </div>
        <div style={{fontSize:15, color:'rgba(255,255,255,0.7)', marginTop:8, textAlign:'center', maxWidth:280}}>
          You're now the {claimed[0]?.titleOverride || s.itemById[itemId].title} in {claimed.length} group{claimed.length===1?'':'s'}.
        </div>
        <div style={{display:'flex', gap:8, marginTop:26, flexWrap:'wrap', justifyContent:'center', maxWidth:300}}>
          {claimed.map(g=>(
            <div key={g.id} style={{
              padding:'6px 12px', borderRadius:999, background:'rgba(255,255,255,0.12)',
              fontSize:12.5, fontWeight:600, letterSpacing:'-.01em',
            }}>{g.name}</div>
          ))}
        </div>
        <style>{`@keyframes crownPop { 0%{transform:scale(.2) rotate(-30deg); opacity:0} 100%{transform:scale(1) rotate(0); opacity:1} }`}</style>
      </div>
    );
  }

  return null;
}

Object.assign(window, { SpotFlow });
