/* ───────────────────────────────────────────────────────────
   ui.jsx — shared primitives
   Exports: Screen, Wordmark, BackBar, BottomNav, Stepper, Donut,
   CountRing, Sheet, Sidebar, PushBanner, ProfileSigil, VerdictPill,
   Bar, Stat, Segmented
   ─────────────────────────────────────────────────────────── */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* full screen scroll surface; dark flips status-bar handled by app */
function Screen({ children, bg='var(--cream)', pad=true, style={} }) {
  return (
    <div className="app-scroll" style={{ background:bg, minHeight:'100%', ...style }}>
      <div style={{ padding: pad ? '58px 22px 108px' : 0 }}>{children}</div>
    </div>
  );
}

/* brand wordmark — Scuola di Stile lockup in miniature */
function Wordmark({ color='var(--navy)', size=15, sub=true }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:9 }}>
      <Hexmark size={size*1.7}/>
      <div style={{ lineHeight:1 }}>
        <div className="serif" style={{ fontSize:size, color, letterSpacing:.2, fontWeight:600 }}>Scuola di Stile</div>
        {sub && <div style={{ fontSize:size*0.52, letterSpacing:'.22em', textTransform:'uppercase', color:'var(--ink-faint)', marginTop:3, fontWeight:700 }}>Decluttering</div>}
      </div>
    </div>
  );
}
function Hexmark({ size=26 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 40 40" style={{display:'block'}}>
      <path d="M20 2.5L35.6 11v18L20 37.5 4.4 29V11L20 2.5z" fill="#dceaf0" stroke="var(--sky-600)" strokeWidth="1"/>
      <text x="20" y="26.5" textAnchor="middle" fontFamily="Playfair Display, serif" fontSize="19" fontStyle="italic" fill="var(--navy)">S</text>
    </svg>
  );
}

function BackBar({ onBack, title, right=null, dark=false }) {
  const c = dark? '#fff':'var(--navy)';
  return (
    <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
      {onBack && (
        <button onClick={onBack} aria-label="Indietro" style={{
          width:40, height:40, borderRadius:999, border:'none', cursor:'pointer',
          background: dark?'rgba(255,255,255,.12)':'rgba(0,34,85,.06)',
          display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
          {Icon.chevL({ color:c, size:20 })}
        </button>
      )}
      {title && <div className="serif" style={{ fontSize:20, color:c, flex:1 }}>{title}</div>}
      {right}
    </div>
  );
}

/* bottom tab bar */
function BottomNav({ tab, onTab }) {
  const tabs=[
    { id:'home', label:'Oggi', icon:Icon.home },
    { id:'sessions', label:'Sessioni', icon:Icon.layers },
    { id:'insights', label:'Stile', icon:Icon.chart },
  ];
  return (
    <div style={{
      position:'absolute', left:0, right:0, bottom:0, zIndex:40,
      padding:'10px 26px 30px', display:'flex', justifyContent:'space-around',
      background:'linear-gradient(180deg, rgba(251,247,243,0) 0%, var(--cream) 38%)',
    }}>
      {tabs.map(t=>{
        const on = tab===t.id;
        return (
          <button key={t.id} onClick={()=>onTab(t.id)} style={{
            border:'none', background:'none', cursor:'pointer', flex:1,
            display:'flex', flexDirection:'column', alignItems:'center', gap:4 }}>
            {t.icon({ color: on?'var(--magenta)':'var(--ink-faint)', size:23, sw: on?2.1:1.7 })}
            <span style={{ fontSize:10.5, fontWeight:700, letterSpacing:'.04em',
              color: on?'var(--magenta)':'var(--ink-faint)' }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

/* step progress (quiz / questions) */
function Stepper({ n, i, color='var(--magenta)' }) {
  return (
    <div style={{ display:'flex', gap:6 }}>
      {Array.from({length:n}).map((_,k)=>(
        <div key={k} style={{ height:4, flex:1, borderRadius:4, transition:'background .3s',
          background: k<=i ? color : 'rgba(0,34,85,.12)' }}/>
      ))}
    </div>
  );
}

/* donut: kept vs given */
function Donut({ kept, given, size=132, stroke=18 }) {
  const total=Math.max(1,kept+given);
  const r=(size-stroke)/2, C=2*Math.PI*r;
  const keepLen=C*(kept/total);
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--neg)" strokeWidth={stroke} opacity={given?1:.18}/>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--pos)" strokeWidth={stroke}
        strokeDasharray={`${keepLen} ${C-keepLen}`} strokeDashoffset={C*0.25} strokeLinecap="butt"
        transform={`rotate(-0 ${size/2} ${size/2})`}/>
      <text x={size/2} y={size/2-2} textAnchor="middle" className="serif" fontSize={size*0.27} fill="var(--navy)">{Math.round(kept/total*100)}%</text>
      <text x={size/2} y={size/2+16} textAnchor="middle" fontSize={size*0.085} fill="var(--ink-soft)" letterSpacing="1.5" style={{textTransform:'uppercase',fontWeight:700}}>tenuti</text>
    </svg>
  );
}

/* countdown ring for the live session */
function CountRing({ frac, size=232, stroke=12, color='#fff', track='rgba(255,255,255,.18)', children }) {
  const r=(size-stroke)/2, C=2*Math.PI*r;
  return (
    <div style={{ position:'relative', width:size, height:size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{transform:'rotate(-90deg)'}}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={track} strokeWidth={stroke}/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
          strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C*(1-frac)}
          style={{ transition:'stroke-dashoffset 1s linear, stroke .6s' }}/>
      </svg>
      <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>{children}</div>
    </div>
  );
}

/* bottom sheet inside the device */
function Sheet({ open, onClose, children, maxH='86%' }) {
  if(!open) return null;
  return (
    <div style={{ position:'absolute', inset:0, zIndex:60 }}>
      <div onClick={onClose} className="fade-in" style={{ position:'absolute', inset:0, background:'rgba(8,18,38,.42)', backdropFilter:'blur(2px)' }}/>
      <div style={{ position:'absolute', left:0, right:0, bottom:0, maxHeight:maxH,
        background:'var(--paper)', borderRadius:'26px 26px 0 0', boxShadow:'var(--shadow-pop)',
        animation:'slideUpSheet .34s cubic-bezier(.2,.8,.2,1) both', overflow:'hidden',
        display:'flex', flexDirection:'column' }}>
        <div style={{ display:'flex', justifyContent:'center', padding:'10px 0 2px' }}>
          <div style={{ width:38, height:4.5, borderRadius:4, background:'rgba(0,34,85,.16)' }}/>
        </div>
        <div className="app-scroll" style={{ padding:'8px 22px 30px' }}>{children}</div>
      </div>
    </div>
  );
}

/* right-sliding detail sidebar */
function Sidebar({ open, onClose, children }) {
  if(!open) return null;
  return (
    <div style={{ position:'absolute', inset:0, zIndex:60 }}>
      <div onClick={onClose} style={{ position:'absolute', inset:0,
        background:'rgba(8,18,38,.42)', backdropFilter:'blur(2px)', WebkitBackdropFilter:'blur(2px)' }}/>
      <div style={{ position:'absolute', top:0, bottom:0, right:0, width:'87%',
        background:'var(--cream)', boxShadow:'var(--shadow-pop)',
        display:'flex', flexDirection:'column' }}>
        <div className="app-scroll" style={{ padding:'52px 22px 30px', flex:1 }}>{children}</div>
      </div>
    </div>
  );
}

/* iOS push notification banner dropping from the top */
function PushBanner({ data, onClose, onAction }) {
  useEffect(()=>{
    if(!data) return;
    const t=setTimeout(()=>onClose&&onClose(), data.sticky?14000:6000);
    return ()=>clearTimeout(t);
  },[data]);
  if(!data) return null;
  return (
    <div style={{ position:'absolute', top:14, left:10, right:10, zIndex:80,
      animation:'pushDrop .5s cubic-bezier(.2,.9,.2,1) both' }}>
      <div onClick={()=>onAction&&onAction(data)} style={{
        background:'rgba(245,245,250,.82)', backdropFilter:'blur(22px) saturate(180%)',
        WebkitBackdropFilter:'blur(22px) saturate(180%)',
        borderRadius:22, padding:'12px 14px', display:'flex', gap:11, alignItems:'flex-start',
        boxShadow:'0 8px 30px rgba(0,0,0,.18)', border:'.5px solid rgba(255,255,255,.5)', cursor:'pointer' }}>
        <div style={{ width:38, height:38, borderRadius:9, flexShrink:0, overflow:'hidden',
          display:'flex', alignItems:'center', justifyContent:'center', background:'var(--navy)' }}>
          <Hexmark size={26}/>
        </div>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
            <span style={{ fontSize:13, fontWeight:700, color:'#1c1c1e' }}>Decluttering</span>
            <span style={{ fontSize:11.5, color:'rgba(60,60,67,.6)' }}>{data.when||'adesso'}</span>
          </div>
          <div style={{ fontSize:13.5, fontWeight:650, color:'#1c1c1e', marginTop:1 }}>{data.title}</div>
          <div style={{ fontSize:13, color:'rgba(60,60,67,.85)', marginTop:1, lineHeight:1.32 }}>{data.body}</div>
        </div>
      </div>
    </div>
  );
}

function ProfileSigil({ profile, size=92 }) {
  const p=PROFILES[profile]||PROFILES.A;
  return (
    <div style={{ width:size, height:size, borderRadius:'50%', position:'relative',
      display:'flex', alignItems:'center', justifyContent:'center',
      background:p.soft, boxShadow:`inset 0 0 0 1.5px ${p.tint}` }}>
      <div style={{ position:'absolute', inset:7, borderRadius:'50%', border:`1px solid ${p.tint}`, opacity:.35 }}/>
      <span className="serif" style={{ fontSize:size*0.32, fontStyle:'italic', color:p.tint }}>{p.sym}</span>
    </div>
  );
}

function VerdictPill({ v, score, small=false }) {
  const keep=v==='keep';
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:6,
      padding: small?'3px 9px':'5px 12px', borderRadius:999,
      fontSize: small?11:12.5, fontWeight:700, letterSpacing:'.02em',
      color: keep?'var(--pos-700)':'var(--neg-700)',
      background: keep?'rgba(31,138,91,.12)':'rgba(196,60,43,.12)' }}>
      {keep? Icon.check({size:small?12:14, color:'var(--pos-700)', sw:2.4})
           : Icon.gift({size:small?12:14, color:'var(--neg-700)', sw:1.9})}
      {keep?'Resta':'Via'}{score!==undefined && <span className="mono" style={{opacity:.7}}>{score>0?'+':''}{score}</span>}
    </span>
  );
}

function Bar({ value, max=1, color='var(--magenta)', track='rgba(0,34,85,.08)', h=7 }) {
  const pct=Math.max(0,Math.min(100, ((value+ (max)) / (2*max))*100)); // for -max..max scales
  return (
    <div style={{ height:h, borderRadius:h, background:track, overflow:'hidden' }}>
      <div style={{ height:'100%', width:pct+'%', background:color, borderRadius:h, transition:'width .6s cubic-bezier(.2,.8,.2,1)' }}/>
    </div>
  );
}

function Stat({ value, label, color='var(--navy)' }) {
  return (
    <div style={{ textAlign:'center' }}>
      <div className="serif" style={{ fontSize:30, color, lineHeight:1 }}>{value}</div>
      <div style={{ fontSize:11, color:'var(--ink-soft)', marginTop:5, letterSpacing:'.03em', fontWeight:600 }}>{label}</div>
    </div>
  );
}

Object.assign(window, {
  Screen, Wordmark, Hexmark, BackBar, BottomNav, Stepper, Donut, CountRing,
  Sheet, Sidebar, PushBanner, ProfileSigil, VerdictPill, Bar, Stat,
});
