/* ───────────────────────────────────────────────────────────
   session.jsx — live decluttering session
   timer + push reminders · add capo · swipe-to-decide engine
   Exports: SessionScreen
   ─────────────────────────────────────────────────────────── */

const DIRS = {
  right:{ ans:'pos', label:'Sì',     color:'var(--pos)',  x:1,  y:0 },
  left: { ans:'neg', label:'No',     color:'var(--neg)',  x:-1, y:0 },
  up:   { ans:'neu', label:'Neutro', color:'var(--calm)', x:0,  y:-1 },
  down: { ans:'ind', label:'Forse',  color:'#8a7bb0',     x:0,  y:1 },
};

function SessionScreen({ session, speed=60, swipeStyle='deck', keepThreshold=0.5, onFinish, onExit, onNotify }) {
  const total=session.durationMin*60;
  const [left,setLeft]=useState(total);
  const [phase,setPhase]=useState('intro');   // intro · add · swipe · done
  const [items,setItems]=useState([]);
  const [draft,setDraft]=useState(null);
  const [qi,setQi]=useState(0);
  const [answers,setAnswers]=useState({});
  const firedRef=useRef({});
  const startRef=useRef(Date.now());

  // timer
  useEffect(()=>{
    if(phase==='intro'||phase==='done') return;
    const iv=setInterval(()=>{
      setLeft(prev=>{
        const n=Math.max(0, prev-speed);
        [15,10,5].forEach(min=>{
          if(prev>min*60 && n<=min*60 && !firedRef.current[min]){
            firedRef.current[min]=true;
            onNotify&&onNotify({ title:`Mancano ${min} minuti`, body:`La sessione “${secLabel(session)}” sta per chiudersi. Ancora qualche capo!`, when:'adesso' });
          }
        });
        if(prev>0 && n<=0 && !firedRef.current.end){
          firedRef.current.end=true;
          onNotify&&onNotify({ title:'Tempo scaduto', body:'Ottimo lavoro. Guarda i risultati della sessione.', when:'adesso' });
        }
        return n;
      });
    },1000);
    return ()=>clearInterval(iv);
  },[phase,speed]);

  const elapsed=()=> Math.min(total, total-left + (phase==='intro'?0:0));
  const finish=()=> { setPhase('done'); onFinish(items, total-left); };

  const runningScore=useMemo(()=>scoreItem(answers),[answers]);
  const overMin = left<=5*60;

  // ----- add item -----
  const startItem=(d)=>{ setDraft(d); setAnswers({}); setQi(0); setPhase('swipe'); };

  // ----- answer a question -----
  const answer=(dir)=>{
    const ansKey=DIRS[dir].ans;
    const Q=QUESTIONS[qi];
    const next={...answers,[Q.id]:ansKey};
    setAnswers(next);
    if(qi<QUESTIONS.length-1){ setQi(qi+1); }
    else {
      // complete the item
      const it={ ...draft, id:uid(), answers:next, score:scoreItem(next) };
      setItems(list=>[...list,it]);
      setDraft(it);            // keep for the mini-result
      setPhase('itemDone');
    }
  };

  return (
    <div style={{ position:'absolute', inset:0, zIndex:50, background:'#001a44', overflow:'hidden',
      display:'flex', flexDirection:'column', color:'#fff' }}>

      {/* top bar — timer */}
      <div style={{ padding:'52px 18px 10px', display:'flex', alignItems:'center', justifyContent:'space-between', position:'relative', zIndex:5 }}>
        <button onClick={onExit} style={{ width:38, height:38, borderRadius:999, border:'none', background:'rgba(255,255,255,.1)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          {Icon.chevD({ size:20, color:'#fff' })}
        </button>
        <div style={{ textAlign:'center' }}>
          <div style={{ display:'flex', alignItems:'center', gap:7 }}>
            {Icon.clock({ size:15, color: overMin?'#ff9ec4':'var(--sky)' })}
            <span className="mono tnum" style={{ fontSize:19, fontWeight:500, letterSpacing:1, color: overMin?'#ff9ec4':'#fff' }}>{fmtTime(left)}</span>
          </div>
          <div style={{ fontSize:10, letterSpacing:'.12em', textTransform:'uppercase', color:'rgba(255,255,255,.5)', marginTop:2, fontWeight:700 }}>{secLabel(session)} · {items.length} capi</div>
        </div>
        <button onClick={finish} style={{ border:'none', background:'rgba(255,255,255,.1)', color:'#fff', fontFamily:'var(--font-body)', fontSize:12.5, fontWeight:700, padding:'9px 13px', borderRadius:999, cursor:'pointer' }}>Termina</button>
      </div>
      {/* progress of time */}
      <div style={{ height:3, background:'rgba(255,255,255,.1)', margin:'0 18px', borderRadius:3, overflow:'hidden' }}>
        <div style={{ height:'100%', width:(left/total*100)+'%', background: overMin?'var(--magenta)':'var(--sky)', transition:'width 1s linear', borderRadius:3 }}/>
      </div>

      {/* body */}
      <div style={{ flex:1, position:'relative', minHeight:0 }}>
        {phase==='intro' && <IntroPhase session={session} onStart={()=>{ startRef.current=Date.now(); setPhase('add'); }}/>}
        {phase==='add' && <AddItemPhase index={items.length} onAdd={startItem} onFinish={finish} canFinish={items.length>0}/>}
        {phase==='swipe' && <SwipePhase style={swipeStyle} qi={qi} answers={answers} draft={draft} runningScore={runningScore} onAnswer={answer}/>}
        {phase==='itemDone' && <ItemDonePhase item={draft} threshold={keepThreshold}
          onNext={()=>{ setDraft(null); setPhase('add'); }}
          onFinish={finish}/>}
      </div>
    </div>
  );
}
function secLabel(s){ return s.section==='all'?'Guardaroba':catById(s.section).label; }

/* ---- intro ---- */
function IntroPhase({ session, onStart }){
  return (
    <div className="fade-in" style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'0 34px', textAlign:'center' }}>
      <svg viewBox="0 0 200 200" style={{ position:'absolute', width:320, opacity:.13 }}>
        {[50,80,110].map((r,i)=><circle key={i} cx="100" cy="100" r={r} fill="none" stroke="#a8d2e0" strokeWidth="1"/>)}
      </svg>
      <div style={{ position:'relative' }}>
        <div className="eyebrow" style={{ color:'var(--sky)', marginBottom:16 }}>{session.durationMin} minuti · {secLabel(session)}</div>
        <h1 className="serif" style={{ fontSize:34, fontWeight:500, lineHeight:1.15, margin:'0 0 14px' }}>Solo due pile:<br/><span style={{fontStyle:'italic',color:'var(--sky)'}}>resta</span> o <span style={{fontStyle:'italic',color:'#ff9ec4'}}>via</span>.</h1>
        <p style={{ fontSize:15, color:'rgba(255,255,255,.72)', lineHeight:1.5, maxWidth:300, margin:'0 auto 30px' }}>
          Niente “forse”. Per ogni capo rispondi a sei domande con un gesto. Il colore ti dirà dove sta andando la decisione.
        </p>
        <button className="btn btn-primary" onClick={onStart} style={{ padding:'15px 34px' }}>Avvia il timer {Icon.arrowR({size:18,color:'#fff'})}</button>
      </div>
    </div>
  );
}

/* ---- add item ---- */
function AddItemPhase({ index, onAdd, onFinish, canFinish }){
  const [name,setName]=useState('');
  const [cat,setCat]=useState('top');
  const [color,setColor]=useState(SWATCHES[index%SWATCHES.length]);
  const [photo,setPhoto]=useState(false);
  const ready=name.trim().length>0;
  return (
    <div className="fade-in app-scroll" style={{ position:'absolute', inset:0, padding:'18px 22px 24px', overflow:'auto' }}>
      <div className="eyebrow" style={{ color:'var(--sky)', marginBottom:8 }}>Nuovo capo · #{index+1}</div>
      <h2 className="serif" style={{ fontSize:24, fontWeight:500, margin:'0 0 18px' }}>Cosa hai in mano?</h2>

      {/* visual stand-in (photo) */}
      <div style={{ display:'flex', gap:15, alignItems:'center', marginBottom:18 }}>
        <div style={{ width:84, height:84, borderRadius:18, position:'relative', overflow:'hidden', flexShrink:0,
          background:`linear-gradient(150deg, ${color}, ${shade(color,-20)})`, boxShadow:'inset 0 0 0 1px rgba(255,255,255,.12)' }}>
          <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <CatIcon id={cat} size={42} color="rgba(255,255,255,.92)" sw={1.4}/>
          </div>
        </div>
        <div style={{ flex:1 }}>
          <button onClick={()=>setPhoto(p=>!p)} className="btn" style={{ background:'rgba(255,255,255,.12)', color:'#fff', padding:'11px 16px', fontSize:14, width:'100%' }}>
            {Icon.camera({ size:18, color:'#fff' })} {photo?'Foto aggiunta':'Scatta una foto'}
          </button>
          <div style={{ fontSize:11.5, color:'rgba(255,255,255,.5)', marginTop:7, lineHeight:1.4 }}>Consigliata: rende i risultati più facili da rivedere.</div>
        </div>
      </div>

      {/* color stand-in */}
      <div style={{ display:'flex', gap:8, marginBottom:18, flexWrap:'wrap' }}>
        {SWATCHES.slice(0,8).map(c=>(
          <button key={c} onClick={()=>setColor(c)} style={{ width:30, height:30, borderRadius:9, border:'none', cursor:'pointer', background:c,
            boxShadow: color===c?'0 0 0 2px #001a44, 0 0 0 4px #fff':'inset 0 0 0 1px rgba(255,255,255,.15)' }}/>
        ))}
      </div>

      <label style={{ fontSize:12, fontWeight:700, color:'rgba(255,255,255,.6)', display:'block', marginBottom:7, letterSpacing:'.02em' }}>NOME DEL CAPO</label>
      <input autoFocus value={name} onChange={e=>setName(e.target.value)} placeholder="es. Camicia di lino bianca"
        style={{ width:'100%', background:'rgba(255,255,255,.08)', border:'1.5px solid rgba(255,255,255,.18)', color:'#fff',
          borderRadius:14, padding:'14px 16px', fontSize:16, fontFamily:'var(--font-body)', outline:'none', marginBottom:18 }}/>

      <label style={{ fontSize:12, fontWeight:700, color:'rgba(255,255,255,.6)', display:'block', marginBottom:10, letterSpacing:'.02em' }}>CATEGORIA</label>
      <div style={{ display:'flex', flexWrap:'wrap', gap:8, marginBottom:24 }}>
        {CATEGORIES.map(c=>(
          <button key={c.id} onClick={()=>setCat(c.id)} style={{ display:'flex', alignItems:'center', gap:7, padding:'9px 13px', borderRadius:999, cursor:'pointer', fontFamily:'var(--font-body)', fontSize:13.5, fontWeight:600,
            border:'1.5px solid '+(cat===c.id?'var(--sky)':'rgba(255,255,255,.18)'),
            background: cat===c.id?'rgba(168,210,224,.18)':'transparent', color: cat===c.id?'#fff':'rgba(255,255,255,.7)' }}>
            <CatIcon id={c.id} size={17} color={cat===c.id?'var(--sky)':'rgba(255,255,255,.6)'}/>{c.label}
          </button>
        ))}
      </div>

      <button className="btn btn-primary btn-block" disabled={!ready} onClick={()=>onAdd({ name:name.trim(), category:cat, color, photo:null })}>
        Inizia le domande {Icon.arrowR({size:18,color:'#fff'})}
      </button>
      {canFinish && (
        <button onClick={onFinish} style={{ width:'100%', marginTop:12, background:'none', border:'none', color:'rgba(255,255,255,.6)', fontFamily:'var(--font-body)', fontSize:14, fontWeight:600, cursor:'pointer' }}>
          Termina la sessione
        </button>
      )}
    </div>
  );
}

Object.assign(window, { SessionScreen, DIRS, secLabel });
