/* ============================================================
   DASHBOARD
   ============================================================ */

function StatCard({ label, value, sub, color, icon, onClick }) {
  const vp = useViewport();
  return (
    <button onClick={onClick} style={{ textAlign:'left', background:'var(--surface)', border:'1px solid var(--line)',
      borderRadius:'var(--r-lg)', padding: vp.isMobile?'14px 15px':'18px 20px', display:'flex', flexDirection:'column', gap:2,
      boxShadow:'var(--sh-1)', transition:'transform .14s, box-shadow .14s', cursor: onClick?'pointer':'default' }}
      onMouseEnter={e=>{ if(onClick){ e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='var(--sh-2)'; } }}
      onMouseLeave={e=>{ e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow='var(--sh-1)'; }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: vp.isMobile?4:8 }}>
        <span style={{ width: vp.isMobile?32:38, height: vp.isMobile?32:38, borderRadius:10, display:'flex', alignItems:'center', justifyContent:'center',
          background:'color-mix(in srgb, '+color+' 12%, var(--surface))', color }}>
          <Icon name={icon} size={vp.isMobile?17:20} />
        </span>
        {onClick && !vp.isMobile && <Icon name="arrowRight" size={17} style={{ color:'var(--ink-4)' }} />}
      </div>
      <div style={{ fontFamily:'var(--font-display)', fontSize: vp.isMobile?24:30, fontWeight:800, letterSpacing:'-.02em', lineHeight:1 }}>{value}</div>
      <div style={{ fontSize: vp.isMobile?12:13, fontWeight:600, color:'var(--ink-2)' }}>{label}</div>
      {sub && !vp.isMobile && <div style={{ fontSize:12, color:'var(--ink-4)', marginTop:2 }}>{sub}</div>}
    </button>
  );
}

function Dashboard({ role, nav, openProduct, setCatFilter, attributi, products, currentUser }) {
  const ALL = products || PRODOTTI;
  // Ubicazione: usa gli attributi "sede", con fallback a posizione (mai "Da definire")
  const sedeNames = (attributi||[]).filter(a=>a.sede).map(a=>a.nome);
  const ubicazioneOf = (p) => {
    const s = sedeNames.map(n => p.attr && p.attr[n]).filter(Boolean).join(' · ');
    return s || (p.posizione && p.posizione!=='Da definire' ? p.posizione : '');
  };
  const visible = ALL.filter(p => p.stato!=='ARCHIVIATO' && (role!=='commerciale' || p.stato!=='NON_VISIBILE'));
  const count = (st) => ALL.filter(p=>p.stato===st).length;
  const recent = ALL.filter(p=>p.stato!=='ARCHIVIATO').slice(0,5);
  const firstName = (currentUser?.nome || '').trim().split(' ')[0]
    || (role==='admin'?'Omar':role==='backoffice'?'Sara':'Marco');
  const user = firstName;
  const vp = useViewport();

  // Watched (tenuti d'occhio)
  const [watchedIds, setWatchedIds] = useState([]);
  useEffect(() => {
    (async () => {
      const ids = await window.WatchAPI?.getMyWatchedIds?.() || [];
      setWatchedIds(ids);
    })();
  }, []);
  const watchedList = ALL.filter(p => watchedIds.includes(p.id) && p.stato !== 'ARCHIVIATO').slice(0, 5);

  const openWatchedInCatalog = () => {
    sessionStorage.setItem('sf_catalog_watched_only', '1');
    nav('catalogo');
  };

  const stats = [
    { label:'Disponibili', value:count('DISPONIBILE'), color:'var(--st-disponibile)', icon:'check', st:'DISPONIBILE' },
    { label:'Prenotati', value:count('PRENOTATO'), color:'var(--st-prenotato)', icon:'calendar', st:'PRENOTATO' },
    { label:'In arrivo', value:count('IN_ARRIVO'), color:'var(--st-inarrivo)', icon:'download', st:'IN_ARRIVO' },
    { label:'In trattativa', value:count('IN_TRATTATIVA'), color:'var(--st-trattativa)', icon:'tag', st:'IN_TRATTATIVA' },
  ];

  const statsCols = vp.isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)';
  const mainCols  = vp.isMobile ? '1fr' : (vp.isTablet ? '1fr' : '1.5fr 1fr');
  const catCols   = vp.isMobile ? '1fr' : '1fr 1fr';
  const pagePad   = vp.isMobile ? '18px 14px 30px' : '26px 30px 40px';

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden', padding:pagePad }}>
      {/* hero */}
      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', flexWrap:'wrap', gap:16, marginBottom: vp.isMobile?18:24 }}>
        <div>
          <div style={{ fontSize:13.5, color:'var(--ink-3)', fontWeight:600 }}>Buongiorno, {user} 👋</div>
          <h2 style={{ margin:'4px 0 0', fontFamily:'var(--font-display)',
            fontSize: vp.isMobile?22:28, fontWeight:800, letterSpacing:'-.02em' }}>
            Ecco la tua flotta oggi
          </h2>
        </div>
        {!vp.isMobile && (
          <div style={{ display:'flex', gap:10 }}>
            <Btn variant="ghost" icon="calendar" onClick={()=>nav('prenotazioni')}>Le mie prenotazioni</Btn>
            <Btn icon="boxes" onClick={()=>nav('catalogo')}>Vai al catalogo</Btn>
          </div>
        )}
      </div>

      {/* stats */}
      <div style={{ display:'grid', gridTemplateColumns:statsCols, gap: vp.isMobile?10:16, marginBottom: vp.isMobile?20:30 }}>
        {stats.map(s => (
          <StatCard key={s.label} {...s} sub={`su ${visible.length} mezzi totali`}
            onClick={()=>{ setCatFilter({stato:s.st}); nav('catalogo'); }} />
        ))}
      </div>

      <div style={{ display:'grid', gridTemplateColumns:mainCols, gap: vp.isMobile?20:24 }}>
        {/* categories */}
        <section>
          <SectionHead title="Categorie" sub="Naviga per tipologia di mezzo" />
          <div style={{ display:'grid', gridTemplateColumns:catCols, gap: vp.isMobile?10:14 }}>
            {CATEGORIE.map(c => {
              const n = ALL.filter(p=>p.cat===c.id && p.stato!=='ARCHIVIATO').length;
              const subAttr = (attributi||[]).find(a=>a.rilievo && a.tipi.includes(c.id));
              const subN = subAttr ? subAttr.termini.length : 0;
              return (
                <button key={c.id} onClick={()=>{ setCatFilter({cat:c.id}); nav('catalogo'); }}
                  style={{ textAlign:'left', background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)',
                    padding: vp.isMobile?'14px 16px':'18px 20px', display:'flex', flexDirection:'column', gap: vp.isMobile?10:14, boxShadow:'var(--sh-1)',
                    transition:'transform .14s, box-shadow .14s' }}
                  onMouseEnter={e=>{ e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='var(--sh-2)'; }}
                  onMouseLeave={e=>{ e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow='var(--sh-1)'; }}>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                    <span style={{ width:46, height:46, borderRadius:12, background:'var(--red-tint)', color:'var(--red)',
                      display:'flex', alignItems:'center', justifyContent:'center' }}>
                      <Icon name={c.icon} size={26} stroke={1.6} />
                    </span>
                    <span style={{ fontFamily:'var(--font-display)', fontSize:26, fontWeight:800, color:'var(--ink)' }}>{n}</span>
                  </div>
                  <div>
                    <div style={{ fontSize:15, fontWeight:700 }}>{c.nome}</div>
                    <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:2 }}>
                      {subN>0 ? subN+' sottocategorie' : 'Categoria unica'}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </section>

        {/* recent */}
        <section>
          <SectionHead title="Ultimi inseriti" sub="Aggiunti di recente" action="Tutti" onAction={()=>nav('catalogo')} />
          <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--sh-1)' }}>
            {recent.map((p,i) => (
              <button key={p.id} onClick={()=>openProduct(p)} style={{ width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:13,
                padding:'12px 16px', borderBottom: i<recent.length-1?'1px solid var(--line-2)':'none', transition:'background .12s' }}
                onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'}
                onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <span style={{ width:46, height:46, borderRadius:9, flexShrink:0, overflow:'hidden',
                  background:'var(--line-2)', border:'1px solid var(--line)' }}>
                  <ProductImage productId={p.id} placeholder={<Icon name={CAT_ICON[p.cat]} size={22} stroke={1.5} />}
                    style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
                </span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13.5, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{prodLabel(p)}</div>
                  <div style={{ fontSize:11.5, color:'var(--ink-3)', fontFamily:'var(--font-display)', fontWeight:600 }}>
                    {[p.matricola, ubicazioneOf(p)].filter(Boolean).join(' · ')}
                  </div>
                </div>
                <StatoBadge stato={p.stato} size="sm" />
              </button>
            ))}
          </div>

          {/* Watched section — appare solo se ci sono mezzi seguiti */}
          {watchedList.length > 0 && (
            <div style={{ marginTop:22 }}>
              <SectionHead
                title={<span style={{ display:'flex', alignItems:'center', gap:7 }}><Icon name="starFilled" size={17} style={{ color:'var(--red)' }} /> Mezzi che stai seguendo</span>}
                sub={`${watchedIds.length} ${watchedIds.length===1?'mezzo':'mezzi'} tenut${watchedIds.length===1?'o':'i'} d'occhio · ricevi notifiche quando cambiano stato`}
                action="Vedi tutti"
                onAction={openWatchedInCatalog} />
              <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--sh-1)' }}>
                {watchedList.map((p,i) => (
                  <button key={p.id} onClick={()=>openProduct(p)} style={{ width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:13,
                    padding:'12px 16px', borderBottom: i<watchedList.length-1?'1px solid var(--line-2)':'none', transition:'background .12s' }}
                    onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'}
                    onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                    <span style={{ width:46, height:46, borderRadius:9, flexShrink:0, overflow:'hidden',
                      background:'var(--line-2)', border:'1px solid var(--line)' }}>
                      <ProductImage productId={p.id} placeholder={<Icon name={CAT_ICON[p.cat]} size={22} stroke={1.5} />}
                        style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
                    </span>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13.5, fontWeight:700, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{prodLabel(p)}</div>
                      <div style={{ fontSize:11.5, color:'var(--ink-3)', fontFamily:'var(--font-display)', fontWeight:600 }}>
                        {[p.matricola, ubicazioneOf(p)].filter(Boolean).join(' · ')}
                      </div>
                    </div>
                    <StatoBadge stato={p.stato} size="sm" />
                  </button>
                ))}
              </div>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}

function SectionHead({ title, sub, action, onAction }) {
  return (
    <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom:14 }}>
      <div>
        <h3 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:17, fontWeight:800, letterSpacing:'-.01em' }}>{title}</h3>
        {sub && <div style={{ fontSize:12.5, color:'var(--ink-3)', marginTop:2 }}>{sub}</div>}
      </div>
      {action && (
        <button onClick={onAction} style={{ display:'flex', alignItems:'center', gap:5, fontSize:13, fontWeight:700, color:'var(--red)' }}>
          {action} <Icon name="chevRight" size={15} />
        </button>
      )}
    </div>
  );
}

Object.assign(window, { Dashboard, StatCard, SectionHead });