// sc-ui.jsx — shared UI primitives for SpotCrown prototype

// Icons ────────────────────────────────────────────────────────────────
function Crown({ size=16, color='var(--crown)', filled=true }){
  return (
    <svg width={size} height={size*0.8} viewBox="0 0 24 20" fill="none">
      <path d="M2 6l3.2 2.4L8 3.5 12 8l4-4.5 2.8 4.9L22 6v10a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"
        fill={filled?color:'none'} stroke={color} strokeWidth="1.4" strokeLinejoin="round"/>
      <circle cx="2" cy="6" r="1.5" fill={color}/>
      <circle cx="12" cy="3" r="1.5" fill={color}/>
      <circle cx="22" cy="6" r="1.5" fill={color}/>
    </svg>
  );
}
function Icon({ name, size=22, color='currentColor', stroke=1.8 }){
  const p = { fill:'none', stroke:color, strokeWidth:stroke, strokeLinecap:'round', strokeLinejoin:'round' };
  switch(name){
    case 'home':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M3 11l9-8 9 8M5 10v10a1 1 0 001 1h4v-7h4v7h4a1 1 0 001-1V10"/></svg>;
    case 'bolt':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>;
    case 'people':   return <svg width={size} height={size} viewBox="0 0 24 24"><circle {...p} cx="9" cy="8" r="3.5"/><circle {...p} cx="17" cy="9" r="2.5"/><path {...p} d="M2.5 20c.8-3.2 3.4-5 6.5-5s5.7 1.8 6.5 5M15 20c.6-2.2 2.2-3.5 4.5-3.5"/></svg>;
    case 'gear':     return <svg width={size} height={size} viewBox="0 0 24 24"><circle {...p} cx="12" cy="12" r="3"/><path {...p} d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3h.1a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8v.1a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg>;
    case 'plus':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M12 5v14M5 12h14"/></svg>;
    case 'chev':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M9 6l6 6-6 6"/></svg>;
    case 'back':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M15 6l-6 6 6 6"/></svg>;
    case 'x':        return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M6 6l12 12M18 6L6 18"/></svg>;
    case 'cam':      return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M4 8h3l2-2h6l2 2h3a1 1 0 011 1v9a1 1 0 01-1 1H4a1 1 0 01-1-1V9a1 1 0 011-1z"/><circle {...p} cx="12" cy="13" r="3.5"/></svg>;
    case 'check':    return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M5 12l4 4 10-10"/></svg>;
    case 'flame':    return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M12 3c1 4 5 5 5 10a5 5 0 11-10 0c0-3 2-4 2-7 2 1 3 0 3-3z"/></svg>;
    case 'hash':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M4 9h16M4 15h16M10 3L8 21M16 3l-2 18"/></svg>;
    case 'share':    return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M12 3v13M7 8l5-5 5 5M5 13v6a1 1 0 001 1h12a1 1 0 001-1v-6"/></svg>;
    case 'bell':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M6 10a6 6 0 1112 0c0 4 2 5 2 7H4c0-2 2-3 2-7zM10 20a2 2 0 004 0"/></svg>;
    case 'search':   return <svg width={size} height={size} viewBox="0 0 24 24"><circle {...p} cx="11" cy="11" r="7"/><path {...p} d="M20 20l-4-4"/></svg>;
    case 'qr':       return <svg width={size} height={size} viewBox="0 0 24 24"><rect {...p} x="3" y="3" width="7" height="7"/><rect {...p} x="14" y="3" width="7" height="7"/><rect {...p} x="3" y="14" width="7" height="7"/><path {...p} d="M14 14h3v3M20 14v7M14 20h3"/></svg>;
    case 'copy':     return <svg width={size} height={size} viewBox="0 0 24 24"><rect {...p} x="8" y="8" width="12" height="12" rx="2"/><path {...p} d="M4 16V6a2 2 0 012-2h10"/></svg>;
    case 'flash':    return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>;
    case 'flip':     return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M3 7a4 4 0 014-4h10a4 4 0 014 4v10a4 4 0 01-4 4H7M3 12l3 3 3-3M6 15v-3"/></svg>;
    case 'arrow-r':  return <svg width={size} height={size} viewBox="0 0 24 24"><path {...p} d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case 'dots':     return <svg width={size} height={size} viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.8" fill={color}/><circle cx="12" cy="12" r="1.8" fill={color}/><circle cx="19" cy="12" r="1.8" fill={color}/></svg>;
    default: return null;
  }
}

// Crown badge overlaid on an item/avatar
function CrownBadge({size=22, position='tr'}){
  const pos = { tr:{top:-6,right:-6}, tl:{top:-6,left:-6}, bl:{bottom:-4,left:-4}, br:{bottom:-4,right:-4} }[position];
  return (
    <div style={{
      position:'absolute', ...pos,
      width:size+6, height:size+6, borderRadius:'50%',
      background:'var(--crown)', display:'flex', alignItems:'center', justifyContent:'center',
      boxShadow:'0 2px 4px rgba(0,0,0,0.15), 0 0 0 2px #fff',
    }}>
      <Crown size={size-6} color="#fff"/>
    </div>
  );
}

// Status bar pill (used atop non-chrome screens)
const NAVBAR_H = 54;
const TABBAR_H = 86;
const STATUS_H = 62; // status bar height (matches IOSStatusBar: 21+22+19 = 62)

// Nav bar — large title OR compact with back
function NavBar({ title, onBack, right, compact=false, subtitle }){
  if (compact){
    // Compact: 44-height centered title row with optional back/right
    return (
      <div style={{padding:'6px 16px 6px', background:'transparent'}}>
        <div style={{display:'flex', alignItems:'center', height:44, justifyContent:'space-between', position:'relative'}}>
          <div style={{display:'flex',alignItems:'center',gap:2, minWidth:44, zIndex:2}}>
            {onBack && (
              <button onClick={onBack} className="tap" style={{
                border:'none', background:'transparent', padding:'6px 6px 6px 0',
                display:'flex', alignItems:'center', gap:2, color:'var(--crown-2)', fontSize:17,
              }}>
                <Icon name="back" size={22} color="var(--crown-2)" stroke={2.2}/>
              </button>
            )}
          </div>
          <div style={{position:'absolute', left:0, right:0, textAlign:'center', fontWeight:600, fontSize:17, pointerEvents:'none'}}>{title}</div>
          <div style={{zIndex:2}}>{right}</div>
        </div>
      </div>
    );
  }
  // Large-title: title + right button share a single row (iOS convention)
  return (
    <div style={{padding:'4px 20px 8px', background:'transparent'}}>
      <div style={{display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12}}>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:32, fontWeight:500, letterSpacing:'-0.02em', color:'var(--ink)', lineHeight:1.1}}>{title}</div>
          {subtitle && <div style={{marginTop:4, fontSize:13.5, color:'var(--muted)'}}>{subtitle}</div>}
        </div>
        {right && <div style={{paddingTop:4, flexShrink:0}}>{right}</div>}
      </div>
    </div>
  );
}

// 5-tab bar — no FAB. Spotting is contextual (per group / per peek), not a global mode.
function TabBar({ active, onChange, badges={} }){
  const tabs = [
    { id:'home',     label:'Home',      icon:'home' },
    { id:'groups',   label:'Groups',    icon:'people' },
    { id:'inperson', label:'In Person', icon:'qr' },
    { id:'activity', label:'Activity',  icon:'bolt' },
    { id:'settings', label:'You',       icon:'gear' },
  ];
  return (
    <div style={{
      position:'absolute', left:0, right:0, bottom:0,
      paddingBottom:28, paddingTop:6,
      display:'flex', alignItems:'flex-end', justifyContent:'space-around',
      background:'rgba(255,255,255,0.85)',
      backdropFilter:'blur(20px) saturate(180%)',
      WebkitBackdropFilter:'blur(20px) saturate(180%)',
      borderTop:'0.5px solid rgba(15,17,21,0.06)',
      zIndex:20,
    }}>
      {tabs.map(t => {
        const on = active===t.id;
        const badge = badges[t.id];
        return (
          <button key={t.id} onClick={()=>onChange(t.id)} className="tap" style={{
            border:'none', background:'transparent', padding:'6px 10px',
            display:'flex', flexDirection:'column', alignItems:'center', gap:2,
            position:'relative', zIndex:1, minWidth:60,
          }}>
            <div style={{position:'relative'}}>
              <Icon name={t.icon} size={24} color={on?'var(--crown-2)':'var(--muted)'} stroke={on?2:1.8}/>
              {badge>0 && (
                <div style={{
                  position:'absolute', top:-4, right:-7, minWidth:16, height:16, padding:'0 4px',
                  borderRadius:8, background:'var(--danger)', color:'#fff', fontSize:10, fontWeight:700,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  boxShadow:'0 0 0 1.5px #fff',
                }}>{badge>9?'9+':badge}</div>
              )}
            </div>
            <div style={{fontSize:10.5, fontWeight:on?600:500, color:on?'var(--crown-2)':'var(--muted)'}}>{t.label}</div>
          </button>
        );
      })}
    </div>
  );
}

// Device-wide screen container that holds a stack of screens; top one visible.
function Screen({ bg='var(--bg)', children, topInset=true }){
  return (
    <div className="screen" style={{
      position:'absolute', inset:0, overflow:'auto', background:bg,
      paddingTop: topInset ? STATUS_H : 0,
    }}>{children}</div>
  );
}
// Dim scrollable content that sits ABOVE tab bar — pads bottom
function ScrollBody({ children, pad=20, bottom=TABBAR_H+16 }){
  return (
    <div style={{padding:`0 ${pad}px ${bottom}px`}}>{children}</div>
  );
}

// Reusable card
function Card({ children, style={}, onClick }){
  return (
    <div onClick={onClick} className={onClick?'tap':''} style={{
      background:'#fff', borderRadius:16, padding:16,
      boxShadow:'0 1px 2px rgba(15,17,21,0.04), 0 0 0 0.5px rgba(15,17,21,0.05)',
      ...style,
    }}>{children}</div>
  );
}

// Tag / chip
function Chip({ children, tone='neutral', style={} }){
  const tones = {
    neutral:{bg:'var(--chip)', fg:'var(--ink-2)'},
    crown:  {bg:'var(--crown-soft)', fg:'var(--crown-2)'},
    rival:  {bg:'var(--rival-soft)', fg:'var(--rival)'},
    ok:     {bg:'#D8ECDC', fg:'var(--ok)'},
  };
  const t = tones[tone]||tones.neutral;
  return <span style={{
    display:'inline-flex', alignItems:'center', gap:4,
    background:t.bg, color:t.fg, borderRadius:999, padding:'3px 10px',
    fontSize:12, fontWeight:600, letterSpacing:'-.01em', ...style,
  }}>{children}</span>;
}

// Avatar round image
function Ava({ person, size=36, ring=false, crown=false }){
  if (!person) return <div style={{width:size,height:size,borderRadius:'50%',background:'var(--chip)'}}/>;
  return (
    <div style={{position:'relative', width:size, height:size, flexShrink:0}}>
      <img src={person.avatar} style={{
        width:size, height:size, borderRadius:'50%', display:'block',
        boxShadow: ring ? '0 0 0 2.5px var(--crown), 0 0 0 4px #fff' : 'none',
      }}/>
      {crown && (
        <div style={{
          position:'absolute', top:-4, left:'50%', transform:'translateX(-50%) rotate(-6deg)',
        }}>
          <Crown size={size*0.42} color="var(--crown)"/>
        </div>
      )}
    </div>
  );
}

// Item tile (square-ish, with emoji on tint) — used in rows and catalog
function ItemTile({ item, size=44, rounded=12 }){
  // Use gradient + emoji directly — no dependency on external image
  const tints = {
    rooster:['#F5D7B8','#E08A3A'], tanuki:['#EADBC0','#8C6B3D'], maneki:['#F6DCDC','#CF8080'],
    torii:['#F1CFC4','#B05238'],   daruma:['#F7CFC0','#B84C38'],  matcha:['#DDEBC9','#6B9452'],
    stolper:['#EFE1B8','#8C6E2B'], phone:['#F2C6C0','#AA3A2A'],   azulejo:['#D5E3EF','#3E6E99'],
    lovelock:['#E9D7C3','#8E6B3B'],tuktuk:['#F3D9B8','#C17A2A'],
  };
  const [a,b] = tints[item?.id] || ['#F4E7CE','#C9A66B'];
  return (
    <div style={{
      width:size, height:size, borderRadius:rounded, flexShrink:0,
      background:`linear-gradient(150deg, ${a}, ${b})`,
      display:'flex', alignItems:'center', justifyContent:'center',
      fontSize:Math.floor(size*0.55), lineHeight:1,
      boxShadow:'inset 0 -2px 6px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.3)',
    }}>
      <span>{item?.emoji}</span>
    </div>
  );
}

// Photo placeholder — gradient + emoji (renders reliably in screenshots too)
function PhotoBG({ emoji, seed='x', style={}, children }){
  const tints = [
    ['#EADFC6','#C9A66B'], ['#D7E4CE','#6B9A72'], ['#E4D7E9','#8B6BA5'],
    ['#D8E2EE','#6B84A5'], ['#EED5CB','#B57058'], ['#F0E6C0','#AF8B3A'],
  ];
  const s = (emoji||'')+ (seed||'');
  const h = Math.abs([...s].reduce((a,c)=>a*31+c.charCodeAt(0),0));
  const [a,b] = tints[h % tints.length];
  return (
    <div style={{
      background:`linear-gradient(135deg, ${a} 0%, ${b} 100%)`,
      display:'flex', alignItems:'center', justifyContent:'center',
      position:'relative', overflow:'hidden', ...style,
    }}>
      <div style={{position:'absolute', inset:0, backgroundImage:'repeating-linear-gradient(35deg, rgba(255,255,255,0.08) 0 10px, transparent 10px 22px)'}}/>
      <div style={{position:'absolute', width:'55%', aspectRatio:'1/1', borderRadius:'50%', background:'rgba(0,0,0,0.12)'}}/>
      <span style={{fontSize:'2.6em', position:'relative', lineHeight:1}}>{emoji}</span>
      {children}
    </div>
  );
}

// Sheet / modal overlay living inside a device
function Sheet({ open, onClose, children, height='88%', dark=false }){
  return (
    <div style={{
      position:'absolute', inset:0, zIndex:40, pointerEvents: open?'auto':'none',
    }}>
      <div onClick={onClose} style={{
        position:'absolute', inset:0, background:'rgba(20,17,12,0.45)',
        opacity: open?1:0, transition:'opacity 240ms ease',
      }}/>
      <div style={{
        position:'absolute', left:0, right:0, bottom:0, height, zIndex:2,
        background: dark ? '#0F1115' : '#FFFFFF',
        borderTopLeftRadius:28, borderTopRightRadius:28,
        transform: open?'translateY(0)':'translateY(102%)',
        transition:'transform 320ms cubic-bezier(.2,.8,.2,1)',
        boxShadow:'0 -12px 40px rgba(0,0,0,0.18)',
        overflow:'hidden', display:'flex', flexDirection:'column',
      }}>
        <div style={{display:'flex',justifyContent:'center',padding:'10px 0 4px'}}>
          <div style={{width:36,height:5,borderRadius:3,background:dark?'rgba(255,255,255,0.3)':'rgba(0,0,0,0.14)'}}/>
        </div>
        {children}
      </div>
    </div>
  );
}

// Primary / secondary button
function Btn({ kind='primary', children, onClick, style={}, leading, full=true, disabled }){
  const kinds = {
    primary:{ bg:'linear-gradient(160deg, var(--crown-glow), var(--crown))', color:'#1A1100',
      shadow:'0 6px 18px rgba(245,179,36,0.4)'},
    secondary:{ bg:'#fff', color:'var(--ink)', shadow:'0 0 0 1px var(--hair)'},
    ghost:{ bg:'transparent', color:'var(--crown-2)', shadow:'none'},
    danger:{ bg:'#fff', color:'var(--danger)', shadow:'0 0 0 1px var(--hair)'},
  };
  const k = kinds[kind];
  return (
    <button onClick={onClick} disabled={disabled} className="tap" style={{
      width: full?'100%':'auto', border:'none', borderRadius:14, padding:'14px 18px',
      background:k.bg, color:k.color, fontSize:16, fontWeight:600,
      letterSpacing:'-.01em', boxShadow:k.shadow, cursor:'pointer',
      display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
      opacity:disabled?.5:1,
      ...style,
    }}>{leading}{children}</button>
  );
}

// Seg-control (iOS)
function Seg({ options, value, onChange, style={} }){
  return (
    <div style={{
      display:'grid', gridTemplateColumns:`repeat(${options.length},1fr)`, gap:2,
      background:'var(--chip)', borderRadius:10, padding:2, ...style,
    }}>
      {options.map(o=>{
        const on = value===o.value;
        return (
          <button key={o.value} onClick={()=>onChange(o.value)} className="tap" style={{
            border:'none', padding:'6px 8px', borderRadius:8, cursor:'pointer',
            background: on?'#fff':'transparent',
            color: on?'var(--ink)':'var(--ink-2)',
            fontSize:13, fontWeight:600,
            boxShadow: on?'0 1px 2px rgba(0,0,0,0.06)':'none',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  Crown, Icon, CrownBadge, NavBar, TabBar, Screen, ScrollBody,
  Card, Chip, Ava, ItemTile, Sheet, Btn, Seg, PhotoBG,
  NAVBAR_H, TABBAR_H, STATUS_H,
});
