/* ───────────────────────────────────────────────────────────
   engine.jsx — seed history, analytics, session planner
   Exports to window: makeItem, seedSessions, buildAnalytics, planSessions
   ─────────────────────────────────────────────────────────── */

function makeItem(name, category, color, a){
  // a = [q1,q2,q3,q4,q5,q6] each 'pos'|'neg'|'neu'|'ind'
  const answers={}; QUESTIONS.forEach((Q,i)=>answers[Q.id]=a[i]);
  const it={ id:uid(), name, category, color, answers, photo:null };
  it.score=scoreItem(answers);
  return it;
}
const P='pos',N='neg',U='neu',I='ind';

/* two completed sessions — a clear story: tops valorize her, bottoms don't */
function seedSessions(){
  const now=Date.now();
  const day=86400000;
  const s1items=[
    makeItem('Camicia di lino bianca','top','#cfd3d8',[P,P,P,U,P,P]),
    makeItem('Maglione cammello','top','#b58a4a',[P,P,P,U,P,P]),
    makeItem('Blusa a fiori','top','#a8556a',[U,P,N,U,P,P]),
    makeItem('T-shirt grafica','top','#56657a',[N,N,P,U,I,N]),
    makeItem('Maglia a coste nera','top','#3d4f6b',[P,P,P,U,P,U]),
    makeItem('Cardigan oversize','capi','#8d8472',[U,P,P,N,U,I]),
    makeItem('Camicia jeans','top','#3d4f6b',[N,U,P,U,N,N]),
  ];
  const s2items=[
    makeItem('Jeans skinny scuri','bottom','#3d4f6b',[N,N,N,U,N,N]),
    makeItem('Jeans boyfriend','bottom','#56657a',[U,N,P,U,N,N]),
    makeItem('Pantalone palazzo','bottom','#46615f',[P,P,P,U,P,P]),
    makeItem('Gonna midi plissé','bottom','#7a5c7d',[P,P,P,U,P,P]),
    makeItem('Pantalone cargo','bottom','#6f7d5a',[N,N,U,N,I,N]),
    makeItem('Leggings neri','bottom','#2c333f',[P,N,P,U,U,N]),
    makeItem('Gonna in pelle','bottom','#9c6b5a',[N,U,N,U,I,I]),
    makeItem('Pantalone sartoriale','bottom','#56657a',[P,P,U,U,P,P]),
  ];
  return [
    { id:uid(), title:'Sessione 1', section:'top', status:'done',
      date:new Date(now-9*day), durationMin:60, elapsedSec:54*60, items:s1items },
    { id:uid(), title:'Sessione 2', section:'bottom', status:'done',
      date:new Date(now-4*day), durationMin:30, elapsedSec:30*60, items:s2items },
  ];
}

/* upcoming planned schedule generated at signup; first one is imminent */
function planSessions(quiz){
  const size = quiz?.g4 || 'B';        // A big · B med · C small
  const cad  = quiz?.g5 || 'B';        // A one long · B few 1h · C many 30m
  const durationMin = cad==='A'?90 : cad==='B'?60 : 30;
  const sections = size==='A'
    ? ['top','bottom','capi','abiti','scarpe','access']
    : size==='B' ? ['top','bottom','capi','access'] : ['top','bottom','capi'];

  const now=Date.now(), hour=3600000, day=86400000;
  const gap = cad==='C' ? 7*day : cad==='B' ? 3*day : 0;
  let out=[];
  if(cad==='A'){
    out.push({ id:uid(), title:'Grande seduta', section:'all', status:'planned',
      date:new Date(now+2.5*hour), durationMin, items:[] });
  } else {
    sections.forEach((sec,i)=>{
      const when = i===0 ? now+2.5*hour : now + i*gap + 9*hour;
      out.push({ id:uid(), title:'Sessione '+(i+1), section:sec, status:'planned',
        date:new Date(when), durationMin, items:[] });
    });
  }
  // a maintenance reminder at the season change
  out.push({ id:uid(), title:'Cambio stagione', section:'all', status:'planned',
    kind:'maintenance', date:new Date(now+38*day), durationMin, items:[] });
  return out;
}

/* ---- analytics over completed sessions ---- */
const SUGGEST = {
  bottom:{ weak:'I pantaloni e le gonne che testi spesso non ti valorizzano.',
           buy:'Punta su modelli a vita alta e gamba fluida: valorizzano più dei tagli aderenti.' },
  top:{ weak:'Diversi top non superano la prova specchio.',
        buy:'Cerca scolli e spalle che incorniciano il viso: lì sei più forte.' },
  capi:{ weak:'Alcuni capispalla ti appesantiscono.',
         buy:'Preferisci linee pulite e lunghezze al ginocchio.' },
  abiti:{ weak:'Qualche abito non ti rappresenta più.', buy:'Cerca abiti che richiamano i tuoi colori migliori.' },
  scarpe:{ weak:'Alcune scarpe restano nell’armadio.', buy:'Investi nei modelli che usi davvero ogni settimana.' },
  access:{ weak:'Diversi accessori non li usi.', buy:'Pochi pezzi versatili battono molti mai indossati.' },
};

function buildAnalytics(sessions){
  const done=sessions.filter(s=>s.status==='done' && s.items.length);
  const all=done.flatMap(s=>s.items);
  const kept=all.filter(i=>verdict(i.score)==='keep');
  const given=all.filter(i=>verdict(i.score)==='give');
  const minutes=done.reduce((t,s)=>t+Math.round((s.elapsedSec||0)/60),0);

  // per category aggregates
  const byCat={};
  for(const c of CATEGORIES) byCat[c.id]={ id:c.id, label:c.label, n:0, sum:0, valor:0, keep:0 };
  for(const it of all){
    const b=byCat[it.category]; if(!b) continue;
    b.n++; b.sum+=it.score;
    b.valor += (ANSWERS[it.answers.q6]?.v ?? 0);
    if(verdict(it.score)==='keep') b.keep++;
  }
  const cats=Object.values(byCat).filter(b=>b.n>0).map(b=>({
    ...b, avg:b.sum/b.n, valorAvg:b.valor/b.n, keepRate:b.keep/b.n,
  })).sort((a,b)=>b.avg-a.avg);

  // per-question average across everything
  const byQ=QUESTIONS.map(Q=>{
    const vals=all.map(i=>ANSWERS[i.answers[Q.id]]?.v ?? 0);
    const avg=vals.length?vals.reduce((a,b)=>a+b,0)/vals.length:0;
    return { id:Q.id, q:Q.q.replace(/\n/g,' '), avg };
  });

  // insights
  const insights=[];
  const strong=cats[0], weak=cats[cats.length-1];
  if(strong && strong.avg>0.6){
    insights.push({ kind:'strength', cat:strong.id, label:strong.label,
      text:`I tuoi ${strong.label.toLowerCase()} sono il tuo punto forte: quasi sempre li tieni.`,
      tip:'Costruisci il guardaroba intorno a questi pezzi.' });
  }
  if(weak && weak.avg<0 && weak.id!==strong?.id){
    const s=SUGGEST[weak.id]||{};
    insights.push({ kind:'weakness', cat:weak.id, label:weak.label,
      text:s.weak||`I tuoi ${weak.label.toLowerCase()} raramente ti convincono.`,
      tip:s.buy||'Rivedi questa categoria al prossimo acquisto.' });
  }
  // valorize-specific
  const lowVal=cats.filter(c=>c.valorAvg< -0.2).sort((a,b)=>a.valorAvg-b.valorAvg)[0];
  if(lowVal && lowVal.id!==weak?.id){
    insights.push({ kind:'valorize', cat:lowVal.id, label:lowVal.label,
      text:`Alla domanda “ti valorizza?” i ${lowVal.label.toLowerCase()} ricevono spesso un no.`,
      tip:(SUGGEST[lowVal.id]||{}).buy||'Sperimenta una linea diversa.' });
  }

  return {
    totals:{ items:all.length, kept:kept.length, given:given.length,
             sessions:done.length, minutes,
             keepPct: all.length? Math.round(kept.length/all.length*100):0 },
    cats, byQ, insights,
  };
}

Object.assign(window, { makeItem, seedSessions, planSessions, buildAnalytics });
