/* ───────────────────────────────────────────────────────────
   app.jsx — root: routing, full-screen mobile shell, push simulator
   ─────────────────────────────────────────────────────────── */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "swipeStyle": "deck",
  "timerSpeed": "×60",
  "keepThreshold": 0.5,
  "accent": "#cc0066",
  "headingFont": "Playfair Display",
  "jumpTo": "—"
}/*EDITMODE-END*/;

const SPEED_MAP={ 'Reale':1, '×10':10, '×60':60 };

function App(){
  // Tweak values are fixed at the mockup defaults — the live Tweaks panel is omitted.
  const t=TWEAK_DEFAULTS;

  // State lives in memory only (no persistence): a page refresh returns to login.
  const [stage,setStage]=useState('auth');
  const [provider,setProvider]=useState('google');
  const [user,setUser]=useState(null);
  const [profile,setProfile]=useState('A');
  const [quiz,setQuiz]=useState(null);
  const [sessions,setSessions]=useState(seedSessions());
  const [tab,setTab]=useState('home');

  const [active,setActive]=useState(null);      // {type:'session'|'results', session}
  const [push,setPush]=useState(null);
  const [resched,setResched]=useState(null);
  const [now,setNow]=useState(Date.now());

  // global clock
  useEffect(()=>{ const iv=setInterval(()=>setNow(Date.now()),1000); return ()=>clearInterval(iv); },[]);

  const speed=SPEED_MAP[t.timerSpeed]||60;
  const threshold=t.keepThreshold;

  // ---- flow handlers ----
  const onProvider=(p)=>{ setProvider(p); setStage('signup'); };
  const onSignup=(f)=>{ setUser(f); setStage('quiz'); };
  const onQuizDone=(ans,prof)=>{ setQuiz(ans); setProfile(prof); setStage('reveal'); };
  const onRevealDone=()=>{ setStage('planning'); };
  const onPlanConfirm=(plan)=>{ setSessions(prev=>[...plan, ...prev.filter(s=>s.status==='done')]); setStage('main'); setTab('home'); };

  const startSession=(s)=>{ setActive({ type:'session', session:s }); setPush(null); };
  const startFree=()=>{
    const dur = quiz?.g5==='C'?30 : quiz?.g5==='A'?90 : 60;
    const s={ id:uid(), title:'Sessione libera', section:'all', status:'planned', date:new Date(), durationMin:Math.min(dur,45), items:[], free:true };
    startSession(s);
  };
  const finishSession=(items, elapsedSec)=>{
    const s=active.session;
    const done={ ...s, status:'done', date:new Date(), elapsedSec, items };
    setSessions(prev=>{
      const exists=prev.some(p=>p.id===s.id);
      const list = exists ? prev.map(p=>p.id===s.id?done:p) : [done,...prev];
      return list;
    });
    setActive({ type:'results', session:done });
  };

  const openResult=(s)=> setActive({ type:'results', session:s });
  const closeOverlay=()=> setActive(null);

  const doReschedule=(s,newDate)=>{
    setSessions(prev=>prev.map(p=>p.id===s.id?{...p,date:newDate}:p));
    setResched(null);
    setPush({ kind:'info', title:'Sessione spostata', body:`“${secLabel(s)}” è ora ${relDay(newDate)}. Ti avviseremo.`, when:'adesso' });
  };

  // ---- push actions ----
  const onPushAction=(d)=>{
    if(d.kind==='reminder'){ const s=sessions.find(x=>x.id===d.sessionId); setPush(null); if(s) startSession(s); }
    else if(d.kind==='missed'){ const s=sessions.find(x=>x.id===d.sessionId); setPush(null); if(s) setResched(s); }
    else setPush(null);
  };
  const simulateReminder=()=>{
    const s=sessions.filter(x=>x.status==='planned'&&x.kind!=='maintenance').sort((a,b)=>a.date-b.date)[0];
    if(!s) return;
    setPush({ kind:'reminder', sessionId:s.id, title:'È quasi ora', body:`La sessione “${secLabel(s)}” inizia tra poco. Pronta?`, when:'adesso', sticky:true });
  };
  const simulateMissed=()=>{
    const s=sessions.filter(x=>x.status==='planned'&&x.kind!=='maintenance').sort((a,b)=>a.date-b.date)[0];
    if(!s) return;
    setPush({ kind:'missed', sessionId:s.id, title:'Sessione saltata', body:'Nessun problema. Vuoi riprogrammarla per un altro momento?', when:'5 min fa', sticky:true });
  };

  let view;

  // base (stage) screen
  let base;
  if(stage==='auth') base=<AuthScreen onProvider={onProvider}/>;
  else if(stage==='signup') base=<SignupScreen provider={provider} onDone={onSignup} onBack={()=>setStage('auth')}/>;
  else if(stage==='quiz') base=<QuizScreen onDone={onQuizDone} onBack={()=>setStage('signup')}/>;
  else if(stage==='reveal') base=<ProfileReveal profile={profile} name={user?.nome} onDone={onRevealDone}/>;
  else if(stage==='planning') base=<PlanningScreen quiz={quiz} onConfirm={onPlanConfirm} onBack={()=>setStage('reveal')}/>;
  else {
    base=(
      <>
        {tab==='home' && <HomeTab user={user} profile={profile} sessions={sessions} now={now}
          onStart={startSession} onOpenResult={openResult} onReschedule={setResched} onFree={startFree} onTab={setTab}/>}
        {tab==='sessions' && <SessionsTab sessions={sessions} now={now} onStart={startSession} onOpenResult={openResult} onReschedule={setResched} onFree={startFree}/>}
        {tab==='insights' && <InsightsTab sessions={sessions} profile={profile}/>}
        <BottomNav tab={tab} onTab={setTab}/>
      </>
    );
  }

  view=(
    <>
      {base}
      {active?.type==='session' && (
        <SessionScreen session={active.session} speed={speed} swipeStyle={t.swipeStyle} keepThreshold={threshold}
          onFinish={finishSession} onExit={closeOverlay} onNotify={(d)=>setPush({...d, kind:'time'})}/>
      )}
      {active?.type==='results' && (
        <div style={{ position:'absolute', inset:0, zIndex:50 }}>
          <ResultsScreen session={active.session} threshold={threshold} onBack={closeOverlay}/>
        </div>
      )}
      <RescheduleSheet s={resched} onClose={()=>setResched(null)} onConfirm={doReschedule}/>
    </>
  );

  return (
    <DeviceStage accent={t.accent} headingFont={t.headingFont}
      push={push} onPushClose={()=>setPush(null)} onPushAction={onPushAction}>
      {view}
    </DeviceStage>
  );
}

/* full-viewport mobile surface + push overlay (no device frame) */
function DeviceStage({ children, accent, headingFont, push, onPushClose, onPushAction }){
  // apply brand accent + heading font as CSS variables
  useEffect(()=>{ document.documentElement.style.setProperty('--magenta', accent); },[accent]);
  useEffect(()=>{ document.documentElement.style.setProperty('--font-display', `"${headingFont}", Georgia, serif`); },[headingFont]);

  return (
    <div className="app-shell">
      {children}
      {/* push notification overlay — only when active */}
      {push && (
        <div style={{ position:'absolute', inset:0, overflow:'hidden', pointerEvents:'none', zIndex:200 }}>
          <div style={{ pointerEvents:'auto' }}>
            <PushBanner data={push} onClose={onPushClose} onAction={onPushAction}/>
          </div>
        </div>
      )}
    </div>
  );
}

/* reschedule bottom sheet */
function RescheduleSheet({ s, onClose, onConfirm }){
  if(!s) return null;
  const base=Date.now();
  const opts=[
    { label:'Più tardi oggi', d:new Date(base+3*3600000) },
    { label:'Domani mattina', d:dayAt(1,9) },
    { label:'Tra 3 giorni', d:dayAt(3,9) },
    { label:'Prossimo weekend', d:nextWeekend() },
  ];
  return (
    <Sheet open={!!s} onClose={onClose}>
      <div className="eyebrow" style={{ color:'var(--magenta)', marginBottom:8 }}>Riprogramma</div>
      <h2 className="serif" style={{ fontSize:23, color:'var(--navy)', margin:'0 0 4px', fontWeight:500 }}>Quando ti va meglio?</h2>
      <p style={{ fontSize:13.5, color:'var(--ink-soft)', margin:'0 0 18px', lineHeight:1.5 }}>
        Spostiamo “{secLabel(s)}”. Nessuna fretta: il decluttering riesce meglio quando lo scegli tu.
      </p>
      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {opts.map((o,i)=>(
          <button key={i} onClick={()=>onConfirm(s,o.d)} className="card" style={{ width:'100%', border:'none', cursor:'pointer', textAlign:'left',
            display:'flex', alignItems:'center', gap:13, padding:'14px 16px' }}>
            <div style={{ width:40, height:40, borderRadius:11, background:'var(--sky-300)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              {Icon.cal({ size:19, color:'var(--navy)' })}
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:15, fontWeight:700, color:'var(--navy)' }}>{o.label}</div>
              <div style={{ fontSize:12.5, color:'var(--ink-soft)' }}>{fullDate(o.d)}</div>
            </div>
            {Icon.chevR({ size:18, color:'var(--ink-faint)' })}
          </button>
        ))}
      </div>
    </Sheet>
  );
}
function dayAt(addDays,h){ const d=new Date(); d.setDate(d.getDate()+addDays); d.setHours(h,0,0,0); return d; }
function nextWeekend(){ const d=new Date(); const day=d.getDay(); const add=(6-day+7)%7||7; d.setDate(d.getDate()+add); d.setHours(10,0,0,0); return d; }
function fullDate(d){
  const g=['domenica','lunedì','martedì','mercoledì','giovedì','venerdì','sabato'][d.getDay()];
  const m=['gen','feb','mar','apr','mag','giu','lug','ago','set','ott','nov','dic'][d.getMonth()];
  return `${g} ${d.getDate()} ${m} · ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
