// WealthIntelligence — Dashboard page
const HomePage = ({state, t, setRoute, openCassettaEditor, openItemDetail, openPersonDetail}) => {
  const unassignedItems = state.inventory.filter(it => !state.cassette.some(c => c.itemIds.includes(it.id)));
  const activeTemporary = state.temporaryIllness?.active;

  // Total wealth
  const valuedItems = state.inventory.filter(it => typeof it.valueEur === 'number' && it.valueEur > 0);
  const totalEur = valuedItems.reduce((s, it) => s + it.valueEur, 0);
  const byCategory = {};
  valuedItems.forEach(it => { byCategory[it.category] = (byCategory[it.category] || 0) + it.valueEur; });
  const sortedCats = Object.entries(byCategory).sort((a,b) => b[1] - a[1]);
  const topCats = sortedCats.slice(0, 4);
  const otherSum = sortedCats.slice(4).reduce((s, [,v]) => s + v, 0);

  const suggestions = [
    {
      id:'cassetta', icon:'vault', tone:'accent',
      title: t.home.action_create_cassetta, desc: t.home.action_create_cassetta_desc,
      action: () => openCassettaEditor(),
    },
    {
      id:'person', icon:'people', tone:'paper',
      title: t.home.action_add_person, desc: t.home.action_add_person_desc,
      action: () => setRoute('trustworthy'),
    },
    {
      id:'inventory', icon:'inventory', tone:'paper',
      title: t.home.action_complete_inventory, desc: t.home.action_complete_inventory_desc,
      action: () => setRoute('inventory'),
    },
  ];

  const recentCassette = state.cassette.slice(0, 3);
  const peopleTop = state.people.slice(0, 5);

  return <div className="fade-in">
    {/* Hero: greeting + total-wealth card */}
    <div style={{display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:36, alignItems:'stretch', marginBottom:32}}>
      <div style={{display:'flex', flexDirection:'column', justifyContent:'flex-end'}}>
        <div className="t-eyebrow" style={{marginBottom:18}}>{t.home.greeting_day}, {state.user.name.split(' ')[0]}</div>
        <h1 className="t-display" style={{fontSize:64, margin:0, lineHeight:0.98}}>
          {t.home.hero_title_1}<br/>
          <span style={{color:'var(--accent-ink)'}}>{t.home.hero_title_2}</span>
        </h1>
        <p style={{marginTop:20, fontSize:16, color:'var(--ink-muted)', maxWidth:540, lineHeight:1.5}}>{t.home.hero_sub}</p>
      </div>

      {/* Total wealth card */}
      <div className="card" style={{padding:28, background:'#fff'}}>
        <div className="t-eyebrow" style={{marginBottom:14}}>{t.home.total_wealth}</div>
        <div className="t-display" style={{fontSize:48, lineHeight:1, margin:'0 0 8px'}}>
          {fmtEur(totalEur)}
        </div>
        <div className="muted" style={{fontSize:13, marginBottom:22}}>
          {t.home.total_wealth_sub
            .replace('{valued}', valuedItems.length)
            .replace('{total}', state.inventory.length)}
        </div>

        <div className="t-eyebrow" style={{marginBottom:10, fontSize:10}}>{t.home.breakdown}</div>
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {topCats.map(([cat, sum]) => {
            const pct = Math.round((sum / totalEur) * 100);
            return <div key={cat}>
              <div className="row" style={{justifyContent:'space-between', marginBottom:4, fontSize:12}}>
                <span style={{fontWeight:500}}>{t.inventory.cat[cat] || cat}</span>
                <span className="muted">{fmtEur(sum)} · {pct}%</span>
              </div>
              <div className="progress"><div style={{width: pct+'%'}}/></div>
            </div>;
          })}
          {otherSum > 0 && (
            <div>
              <div className="row" style={{justifyContent:'space-between', marginBottom:4, fontSize:12}}>
                <span className="muted">Altre categorie</span>
                <span className="muted">{fmtEur(otherSum)} · {Math.round((otherSum/totalEur)*100)}%</span>
              </div>
              <div className="progress"><div style={{width: Math.round((otherSum/totalEur)*100)+'%', background:'var(--gr-400)'}}/></div>
            </div>
          )}
        </div>
      </div>
    </div>

    {/* KPI strip */}
    <div className="card" style={{padding:'18px 24px', marginBottom:40, background:'var(--paper-2)', borderColor:'transparent'}}>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:24}}>
        <KpiCell num={state.cassette.length} label={t.home.kpi_cassette}/>
        <KpiCell num={state.people.length} label={t.home.kpi_people}/>
        <KpiCell num={unassignedItems.length} label={t.home.kpi_unassigned} tone={unassignedItems.length>0?'warn':undefined}/>
      </div>
    </div>

    {/* Active temporary illness banner */}
    {activeTemporary && (
      <div className="card fade-in" style={{padding:20, marginBottom:32, background:'var(--trigger-temporary-soft)', borderColor:'transparent'}}>
        <div className="row" style={{gap:14}}>
          <Icon name="medkit" size={22} style={{color:'var(--trigger-temporary)', flexShrink:0}}/>
          <div className="grow">
            <div style={{fontWeight:600, color:'var(--trigger-temporary)', fontSize:14}}>Modalità infermità temporanea attiva</div>
            <div className="muted" style={{fontSize:13, marginTop:2}}>
              Le cassette con trigger "infermità temporanea" sono accessibili alle persone fidate. Disattiva quando torni operativo.
            </div>
          </div>
          <button className="btn btn-secondary btn-sm" style={{background:'#fff'}} onClick={()=>setRoute('profile')}>
            Vai al profilo <Icon name="arrow_right" size={13}/>
          </button>
        </div>
      </div>
    )}

    {/* Suggestions */}
    <div style={{marginBottom:56}}>
      <SectionHeader eyebrow={t.home.suggestions} title={t.home.suggestions_hero} />
      <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16}}>
        {suggestions.map(s => (
          <div key={s.id} className="card" style={{padding:24, cursor:'pointer', background: s.tone==='accent'?'var(--accent-soft)':'#fff'}} onClick={s.action}>
            <div className="row" style={{justifyContent:'space-between', marginBottom:14}}>
              <span style={{
                width:40, height:40, borderRadius:10,
                background: s.tone==='accent'?'#fff':'var(--paper-2)',
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                color: s.tone==='accent'?'var(--accent-ink)':'var(--ink)',
              }}><Icon name={s.icon} size={20}/></span>
            </div>
            <h3 style={{margin:'0 0 6px', fontSize:17, fontWeight:600}}>{s.title}</h3>
            <p className="muted" style={{margin:0, fontSize:14, lineHeight:1.4}}>{s.desc}</p>
            <div className="row" style={{marginTop:16, color:'var(--ink)', fontSize:13, fontWeight:500, gap:6}}>
              {t.common.continue} <Icon name="arrow_right" size={14}/>
            </div>
          </div>
        ))}
      </div>
    </div>

    {/* Recent cassette */}
    {recentCassette.length > 0 && (
      <div style={{marginBottom:56}}>
        <SectionHeader
          eyebrow={t.home.recent_cassette}
          title="Cassette"
          action={<button className="btn btn-ghost btn-sm" onClick={()=>setRoute('vault')}>{t.home.see_all}<Icon name="arrow_right" size={13}/></button>}
        />
        <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16}}>
          {recentCassette.map(c => {
            const assigned = c.assignees.map(id => state.people.find(p=>p.id===id)).filter(Boolean);
            return <div key={c.id} className="card" style={{padding:20, cursor:'pointer'}} onClick={()=>openCassettaEditor(c)}>
              <div className="row" style={{justifyContent:'space-between', marginBottom:14}}>
                <CassettaBadge icon={c.icon} color={c.color}/>
                <TriggerBadge trigger={c.trigger} t={t} short/>
              </div>
              <div style={{fontFamily:'var(--f-serif)', fontStyle:'italic', fontSize:20, marginBottom:10}}>{c.name}</div>
              <div className="row" style={{justifyContent:'space-between'}}>
                <MonoStack people={assigned}/>
                <span className="muted" style={{fontSize:12}}>{c.itemIds.length} {c.itemIds.length===1?t.vault.item_count_one:t.vault.items_count}</span>
              </div>
            </div>;
          })}
        </div>
      </div>
    )}

    {/* Trustworthy people preview */}
    <div>
      <SectionHeader
        eyebrow={t.home.your_people}
        title="Persone"
        action={<button className="btn btn-ghost btn-sm" onClick={()=>setRoute('trustworthy')}>{t.home.see_all}<Icon name="arrow_right" size={13}/></button>}
      />
      <div className="card" style={{padding:18}}>
        <div style={{display:'grid', gridTemplateColumns:`repeat(${peopleTop.length}, 1fr)`, gap:18}}>
          {peopleTop.map(p => {
            const cassetteCount = state.cassette.filter(c => c.assignees.includes(p.id)).length;
            return <div key={p.id} className="col" style={{alignItems:'center', textAlign:'center', cursor:'pointer'}} onClick={()=>openPersonDetail && openPersonDetail(p)}>
              <Monogram color={p.color} initials={p.initials} size="lg"/>
              <div style={{fontSize:13, fontWeight:500, marginTop:8}}>{p.name.split(' ')[0]}</div>
              <div className="muted" style={{fontSize:11}}>{p.rel}</div>
              <span className="chip chip-muted" style={{marginTop:6, fontSize:10, padding:'2px 8px'}}>
                {cassetteCount} {cassetteCount===1 ? t.trustworthy.cassetta_assigned_one : t.trustworthy.cassette_assigned}
              </span>
            </div>;
          })}
        </div>
      </div>
    </div>
  </div>;
};

Object.assign(window, { HomePage });
