/* ============================================================
   CATALOGO — filtri, ricerca, grid prodotti
   ============================================================ */

// Stati nascosti dal catalogo attivo (visibili solo dal pannello admin → Prodotti)
const HIDDEN_STATI_CATALOGO = ['VENDUTO','NOLEGGIATO','ARCHIVIATO','NON_VISIBILE'];

function PriceLine({ p, role, compact }) {
  const isNoleggio = p.prezzoConsigliato==null && p.prezzoGiorno!=null;
  if (isNoleggio) {
    return (
      <div style={{ display:'flex', alignItems:'baseline', gap:6 }}>
        <span style={{ fontFamily:'var(--font-display)', fontSize:compact?17:20, fontWeight:800 }}>{fmtEur(p.prezzoGiorno)}</span>
        <span style={{ fontSize:12, color:'var(--ink-3)', fontWeight:600 }}>/giorno</span>
      </div>
    );
  }
  return (
    <div>
      <div style={{ display:'flex', alignItems:'baseline', gap:7 }}>
        <span style={{ fontFamily:'var(--font-display)', fontSize:compact?17:21, fontWeight:800 }}>{fmtEur(p.prezzoConsigliato)}</span>
      </div>
      <div style={{ fontSize:11.5, color:'var(--ink-4)', fontWeight:600 }}>prezzo consigliato</div>
    </div>
  );
}

function ProductCard({ p, role, openProduct, onPrenota, attributi }) {
  const cat = CATEGORIE.find(c=>c.id===p.cat);
  // Nomi degli attributi "sede": mostrati come ubicazione (non tra gli attributi tecnici)
  const sedeNames = (attributi||[]).filter(a=>a.sede).map(a=>a.nome);
  const sedeVal = sedeNames.map(n => p.attr && p.attr[n]).filter(Boolean).join(' · ');
  const ubicazione = sedeVal || (p.posizione && p.posizione!=='Da definire' ? p.posizione : null);

  // Attributi in vetrina: mostra prima quelli commercialmente rilevanti per categoria.
  // Match tollerante sul nome (es. "Altezza di sollevamento (mm)" contiene "altezza di sollevamento").
  const PRIORITY_BY_CAT = {
    carrelli:    ['portata', 'altezza di sollevamento', 'anno'],
    piattaforme: ['altezza massima di lavoro', 'portata', 'anno'],
    pulizia:     ['ampiezza di lavoro', 'resa teorica', 'anno'],
    avvolgitrici:['tipologia', 'dimensioni', 'anno'],
  };
  const norm = (s)=>(s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim();
  const entries = Object.entries(p.attr).filter(([k])=>!sedeNames.includes(k));
  const priorities = PRIORITY_BY_CAT[p.cat] || [];
  const picked = [];
  // 1) prendi in ordine gli attributi prioritari se presenti
  for (const pref of priorities) {
    const found = entries.find(([k]) => norm(k).includes(pref) && !picked.includes(k[0]));
    if (found && !picked.some(e=>e[0]===found[0])) picked.push(found);
  }
  // 2) completa fino a 3 con gli altri attributi disponibili (esclusi i già scelti)
  for (const e of entries) {
    if (picked.length >= 3) break;
    if (!picked.some(x=>x[0]===e[0])) picked.push(e);
  }
  const keyAttrs = picked.slice(0,3);
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden',
      display:'flex', flexDirection:'column', boxShadow:'var(--sh-1)', transition:'transform .15s, box-shadow .15s' }}
      onMouseEnter={e=>{ e.currentTarget.style.transform='translateY(-3px)'; e.currentTarget.style.boxShadow='var(--sh-2)'; }}
      onMouseLeave={e=>{ e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow='var(--sh-1)'; }}>
      {/* image */}
      <div style={{ position:'relative' }}>
        <ProductImage productId={p.id} placeholder="Nessuna foto"
          style={{ width:'100%', height:'190px', display:'block' }} />
        <div style={{ position:'absolute', top:11, left:11, zIndex:2 }}><StatoBadge stato={p.stato} size="sm" /></div>
        {p.matricola && (
          <div className="matricola-badge" style={{ position:'absolute', top:11, right:11, zIndex:2, display:'flex', alignItems:'center', gap:6,
            background:'rgba(255,255,255,.92)', padding:'4px 9px', borderRadius:99, fontSize:11, fontWeight:800,
            fontFamily:'var(--font-display)', color:'var(--ink-2)', backdropFilter:'blur(4px)' }}>
            {p.matricola}
          </div>
        )}
        {p.nuovo && <div style={{ position:'absolute', bottom:11, left:11, zIndex:2, fontSize:10.5, fontWeight:800, letterSpacing:'.06em',
          color:'#fff', background:'var(--red)', padding:'3px 9px', borderRadius:99 }}>NUOVO</div>}
      </div>

      {/* body */}
      <div style={{ padding:'15px 17px', display:'flex', flexDirection:'column', flex:1, gap:12 }}>
        <div>
          <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:5 }}>
            <Icon name={cat.icon} size={15} style={{ color:'var(--ink-4)' }} />
            <span style={{ fontSize:11.5, fontWeight:700, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.03em' }}>{cat.nome}</span>
          </div>
          <h3 style={{ margin:0, fontSize:16.5, fontWeight:800, letterSpacing:'-.01em' }}>{p.marca} {p.modello}</h3>
          {ubicazione && (
            <div style={{ display:'flex', alignItems:'center', gap:5, marginTop:4, fontSize:12, color:'var(--ink-3)' }}>
              <Icon name="pin" size={13} /> {ubicazione}
            </div>
          )}
        </div>

        <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
          {keyAttrs.map(([k,v]) => (
            <span key={k} style={{ fontSize:11.5, fontWeight:600, color:'var(--ink-2)', background:'var(--line-2)', padding:'4px 9px', borderRadius:7 }}>
              <span style={{ color:'var(--ink-4)' }}>{k}:</span> {v}
            </span>
          ))}
        </div>

        <div style={{ marginTop:'auto', paddingTop:12, borderTop:'1px solid var(--line-2)', display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:10 }}>
          <PriceLine p={p} role={role} compact />
          <div style={{ display:'flex', gap:7 }}>
            <button onClick={()=>openProduct(p)} title="Apri scheda" style={{ width:36, height:36, borderRadius:9,
              border:'1.5px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)' }}>
              <Icon name="arrowRight" size={17} />
            </button>
            {(() => {
              const nonPrenotabile = ['PRENOTATO','NOLEGGIATO','VENDUTO'].includes(p.stato) || HIDDEN_STATI_CATALOGO.includes(p.stato);
              return (
                <Btn size="sm" onClick={()=>onPrenota(p)} disabled={nonPrenotabile}
                  title={nonPrenotabile ? 'Mezzo non disponibile' : 'Prenota'}>
                  {p.stato==='PRENOTATO' ? 'Prenotato' : p.stato==='NOLEGGIATO' ? 'Noleggiato' : p.stato==='VENDUTO' ? 'Venduto' : 'Prenota'}
                </Btn>
              );
            })()}
          </div>
        </div>
      </div>
    </div>
  );
}

function Catalogo({ role, openProduct, onPrenota, search, catFilter, setCatFilter, attributi, products }) {
  const vp = useViewport();
  const [cat, setCat] = useState(catFilter?.cat || 'all');
  const [stato, setStato] = useState(catFilter?.stato || 'all');
  const [sub, setSub] = useState('all');
  const [dest, setDest] = useState(catFilter?.dest || 'all');
  const [attrVals, setAttrVals] = useState({});
  const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
  const [desktopFiltersOpen, setDesktopFiltersOpen] = useState(false);
  const [showWatchedOnly, setShowWatchedOnly] = useState(false);
  const [watchedIds, setWatchedIds] = useState([]);

  // Carica prodotti tenuti d'occhio dal current user
  useEffect(() => {
    (async () => {
      const ids = await window.WatchAPI?.getMyWatchedIds?.() || [];
      setWatchedIds(ids);
    })();
    // Attiva filtro "solo tenuti d'occhio" se richiesto dalla dashboard
    if (sessionStorage.getItem('sf_catalog_watched_only') === '1') {
      setShowWatchedOnly(true);
      sessionStorage.removeItem('sf_catalog_watched_only');
    }
  }, []);

  useEffect(()=>{ if(catFilter?.cat) setCat(catFilter.cat); if(catFilter?.stato) setStato(catFilter.stato); if(catFilter?.dest) setDest(catFilter.dest); }, [catFilter]);

  const cats = [{id:'all',nome:'Tutte',icon:'grid'}, ...CATEGORIE];
  const activeCat = CATEGORIE.find(c=>c.id===cat);

  // CATALOGO ATTIVO — nascondiamo per tutti i ruoli gli stati: VENDUTO, NOLEGGIATO, ARCHIVIATO, NON_VISIBILE
  // (l'admin vede tutti gli stati dal proprio pannello Prodotti, non da qui)
  let list = (products||PRODOTTI).filter(p => !HIDDEN_STATI_CATALOGO.includes(p.stato));
  if (showWatchedOnly) list = list.filter(p => watchedIds.includes(p.id));
  if (cat!=='all') list = list.filter(p=>p.cat===cat);
  if (sub!=='all') list = list.filter(p=>p.sub===sub);
  if (dest!=='all') list = list.filter(p => (p.liste||[p.dest]).includes(dest));
  if (stato!=='all') list = list.filter(p=>p.stato===stato);
  if (search) {
    const q = search.toLowerCase();
    list = list.filter(p => (p.marca+' '+p.modello+' '+p.id).toLowerCase().includes(q));
  }
  // attribute filters — tolerant match against product attr values
  const activeAttr = Object.entries(attrVals).filter(([,v])=>v && v!=='all');
  if (activeAttr.length && attributi) {
    list = list.filter(p => activeAttr.every(([aid, term]) => {
      const def = attributi.find(a=>a.id===aid); if(!def) return true;
      if (aid.indexOf('sottocat')===0) return p.sub===term; // subcategory lives on p.sub
      const key = Object.keys(p.attr).find(k => normAttr(k)===normAttr(def.nome) || normAttr(k).includes(normAttr(def.nome)) || normAttr(def.nome).includes(normAttr(k)));
      if (!key) return true; // product lacks this attribute — keep (lenient)
      const pv = p.attr[key];
      const digits = s => (s.match(/\d+/g)||[]).join('');
      if (/^[\d.\s]+$/.test(term)) return digits(pv)===digits(term) || pv.includes(term);
      return normAttr(pv).includes(normAttr(term)) || normAttr(term).includes(normAttr(pv));
    }));
  }

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden', display:'flex', flexDirection:'column' }}>
      {/* filter bar */}
      <div style={{ padding: vp.isMobile?'12px 12px 10px':'18px 30px 14px', borderBottom:'1px solid var(--line)', background:'var(--surface)', position:'sticky', top:0, zIndex:10 }}>
        <div className={vp.isMobile?'scroll-x':''} style={{ display:'flex', gap:8,
          flexWrap: vp.isMobile?'nowrap':'wrap', marginBottom:10,
          paddingBottom: vp.isMobile?4:0,
          margin: vp.isMobile?'0 -12px 10px':'0 0 12px',
          padding: vp.isMobile?'0 12px 4px':'0' }}>
          {cats.map(c => {
            const active = cat===c.id;
            return (
              <button key={c.id} onClick={()=>{ setCat(c.id); setSub('all'); setAttrVals({}); setCatFilter({cat:c.id}); }}
                style={{ display:'flex', alignItems:'center', gap:7, padding: vp.isMobile?'8px 13px':'9px 15px', borderRadius:99,
                  fontSize: vp.isMobile?12.5:13.5, fontWeight:700, flexShrink:0,
                  border:'1.5px solid '+(active?'var(--red)':'var(--line)'), background: active?'var(--red)':'var(--surface)', color: active?'#fff':'var(--ink-2)',
                  transition:'.14s' }}>
                <Icon name={c.icon} size={vp.isMobile?14:16} /> {c.nome}
              </button>
            );
          })}
        </div>

        <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
          <div className={vp.isMobile?'scroll-x':''} style={{ display:'flex', gap:6,
            flexWrap: vp.isMobile?'nowrap':'wrap', alignItems:'center',
            margin: vp.isMobile?'0 -12px':'0',
            padding: vp.isMobile?'0 12px 4px':'0',
            width: vp.isMobile?'calc(100% + 24px)':'auto' }}>
            {!vp.isMobile && <span style={{ fontSize:11.5, fontWeight:800, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.04em', marginRight:2 }}>Destinazione</span>}
            <Chip active={dest==='all'} onClick={()=>{ setDest('all'); setCatFilter({...(catFilter||{}), dest:'all'}); }}>Tutte</Chip>
            {['Vendita','STR','LTR','Pronta consegna'].map(d => (
              <Chip key={d} active={dest===d} onClick={()=>{ setDest(d); setCatFilter({...(catFilter||{}), dest:d}); }}>
                {vp.isMobile
                  ? (d==='Pronta consegna' ? 'Nuovo P. consegna' : d)
                  : (d==='STR'?'Noleggio breve (STR)':d==='LTR'?'Noleggio lungo (LTR)':d==='Pronta consegna'?'Nuovo Pronta consegna':d)}
              </Chip>
            ))}
          </div>
          <div style={{ marginLeft: vp.isMobile?0:'auto', display:'flex', alignItems:'center', gap:8, width: vp.isMobile?'100%':'auto', marginTop: vp.isMobile?4:0 }}>
            <div style={{ position:'relative', flex: vp.isMobile?1:'none' }}>
              <select value={stato} onChange={e=>setStato(e.target.value)}
                style={{ appearance:'none', padding:'9px 34px 9px 14px', fontSize:13, fontWeight:600, borderRadius:'var(--r-md)',
                  border:'1.5px solid var(--line)', background:'var(--surface)', color:'var(--ink-2)', cursor:'pointer',
                  width: vp.isMobile?'100%':'auto' }}>
                <option value="all">Tutti gli stati</option>
                {Object.entries(STATI).filter(([k])=>!HIDDEN_STATI_CATALOGO.includes(k)).map(([k,v])=>(
                  <option key={k} value={k}>{v.label}</option>
                ))}
              </select>
              <Icon name="chevDown" size={16} style={{ position:'absolute', right:11, top:'50%', transform:'translateY(-50%)', color:'var(--ink-3)', pointerEvents:'none' }} />
            </div>
            {/* Tieni d'occhio filter toggle */}
            <button onClick={()=>setShowWatchedOnly(v=>!v)} title={showWatchedOnly?'Mostra tutti':'Solo tenute d\'occhio'}
              style={{ padding:'9px 12px', borderRadius:'var(--r-md)', border:'1.5px solid '+(showWatchedOnly?'var(--red)':'var(--line)'),
                background: showWatchedOnly?'var(--red-tint)':'var(--surface)', color: showWatchedOnly?'var(--red)':'var(--ink-2)',
                display:'flex', alignItems:'center', gap:6, fontSize:13, fontWeight:700, whiteSpace:'nowrap', flexShrink:0 }}>
              <Icon name={showWatchedOnly?'starFilled':'star'} size={15} />
              {!vp.isMobile && (showWatchedOnly?'D\'occhio':'Tutti')}
              {watchedIds.length > 0 && <span style={{ background: showWatchedOnly?'var(--red)':'var(--line-2)', color: showWatchedOnly?'#fff':'var(--ink-3)', borderRadius:99, padding:'1px 6px', fontSize:11 }}>{watchedIds.length}</span>}
            </button>
            {/* Attribute filters on mobile → open drawer */}
            {vp.isMobile && (
              <button onClick={()=>setMobileFiltersOpen(true)}
                style={{ padding:'9px 12px', borderRadius:'var(--r-md)', border:'1.5px solid '+(Object.values(attrVals).filter(v=>v&&v!=='all').length>0?'var(--red)':'var(--line)'),
                  background: Object.values(attrVals).filter(v=>v&&v!=='all').length>0?'var(--red-tint)':'var(--surface)',
                  color: Object.values(attrVals).filter(v=>v&&v!=='all').length>0?'var(--red)':'var(--ink-2)',
                  display:'flex', alignItems:'center', gap:6, fontSize:13, fontWeight:700, whiteSpace:'nowrap', flexShrink:0 }}>
                <Icon name="filter" size={15} />
                {Object.values(attrVals).filter(v=>v&&v!=='all').length > 0 && <span style={{ background:'var(--red)', color:'#fff', borderRadius:99, padding:'1px 6px', fontSize:11 }}>{Object.values(attrVals).filter(v=>v&&v!=='all').length}</span>}
              </button>
            )}
            {!vp.isMobile && (
              <button onClick={()=>setDesktopFiltersOpen(v=>!v)}
                style={{ padding:'9px 14px', borderRadius:'var(--r-md)', border:'1.5px solid '+((desktopFiltersOpen||Object.values(attrVals).filter(v=>v&&v!=='all').length>0)?'var(--red)':'var(--line)'),
                  background: (desktopFiltersOpen||Object.values(attrVals).filter(v=>v&&v!=='all').length>0)?'var(--red-tint)':'var(--surface)',
                  color: (desktopFiltersOpen||Object.values(attrVals).filter(v=>v&&v!=='all').length>0)?'var(--red)':'var(--ink-2)',
                  display:'flex', alignItems:'center', gap:7, fontSize:13, fontWeight:700, whiteSpace:'nowrap', cursor:'pointer' }}>
                <Icon name="filter" size={15} />
                Filtri
                {Object.values(attrVals).filter(v=>v&&v!=='all').length > 0 && <span style={{ background:'var(--red)', color:'#fff', borderRadius:99, padding:'1px 6px', fontSize:11 }}>{Object.values(attrVals).filter(v=>v&&v!=='all').length}</span>}
              </button>
            )}
            {!vp.isMobile && <span style={{ fontSize:13, color:'var(--ink-3)', fontWeight:600, whiteSpace:'nowrap' }}>{list.length} mezzi</span>}
          </div>
        </div>
        {vp.isMobile && <div style={{ marginTop:8, fontSize:12, color:'var(--ink-3)', fontWeight:600 }}>{list.length} mezzi</div>}

        {!vp.isMobile && desktopFiltersOpen && (
          <div style={{ marginTop:14, paddingTop:16, borderTop:'1px solid var(--line-2)' }}>
            <CatalogAttrFilters attributi={attributi} cat={cat} values={attrVals} setValues={setAttrVals} />
            {Object.values(attrVals).filter(v=>v&&v!=='all').length > 0 && (
              <button onClick={()=>setAttrVals({})}
                style={{ marginTop:12, padding:'7px 14px', fontSize:12.5, fontWeight:700, color:'var(--ink-3)',
                  background:'var(--line-2)', border:'none', borderRadius:'var(--r-md)', cursor:'pointer' }}>
                Azzera filtri
              </button>
            )}
          </div>
        )}
      </div>

      {/* Mobile filters bottom sheet */}
      {vp.isMobile && mobileFiltersOpen && (
        <div className="no-print" style={{ position:'fixed', inset:0, zIndex:100, background:'rgba(15,17,21,.5)', backdropFilter:'blur(3px)', display:'flex', alignItems:'flex-end' }}
          onClick={()=>setMobileFiltersOpen(false)}>
          <div onClick={e=>e.stopPropagation()} className="scroll modal-mobile" style={{
            width:'100%', maxHeight:'85vh', overflowY:'auto', overflowX:'hidden',
            background:'var(--surface)', borderRadius:'18px 18px 0 0',
            animation:'bsSlideUp .2s cubic-bezier(.2,.7,.3,1)' }}>
            <div style={{ width:38, height:4, background:'var(--line)', borderRadius:99, margin:'10px auto 0' }} />
            <div style={{ padding:'12px 18px 14px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <h2 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:17, fontWeight:800 }}>Filtri</h2>
              <button onClick={()=>setMobileFiltersOpen(false)}
                style={{ width:34, height:34, borderRadius:9, border:'1.5px solid var(--line)', color:'var(--ink-3)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="x" size={17} />
              </button>
            </div>
            <div style={{ padding:'16px' }}>
              <CatalogAttrFilters attributi={attributi} cat={cat} values={attrVals} setValues={setAttrVals} />
            </div>
            <div style={{ padding:'12px 16px', borderTop:'1px solid var(--line)', display:'flex', gap:10, position:'sticky', bottom:0, background:'var(--surface)' }}>
              <Btn variant="ghost" full onClick={()=>{ setAttrVals({}); }}>Azzera</Btn>
              <Btn full onClick={()=>setMobileFiltersOpen(false)}>Applica</Btn>
            </div>
          </div>
        </div>
      )}

      {/* grid */}
      <div style={{ padding: vp.isMobile?'14px 12px 30px':'22px 30px 40px' }}>
        {list.length===0 ? (
          <div style={{ textAlign:'center', padding:'80px 0', color:'var(--ink-3)' }}>
            <Icon name="search" size={36} style={{ margin:'0 auto 12px', opacity:.5 }} />
            <div style={{ fontSize:15, fontWeight:600 }}>Nessun mezzo trovato</div>
          </div>
        ) : (
          <div style={{ display:'grid',
            gridTemplateColumns: vp.isMobile ? '1fr' : (vp.isTablet ? 'repeat(auto-fill, minmax(280px, 1fr))' : 'repeat(auto-fill, minmax(290px, 1fr))'),
            gap: vp.isMobile?14:20 }}>
            {list.map(p => <ProductCard key={p.id} p={p} role={role} openProduct={openProduct} onPrenota={onPrenota} attributi={attributi} />)}
          </div>
        )}
      </div>
    </div>
  );
}

function Chip({ active, onClick, children }) {
  return (
    <button onClick={onClick} style={{ padding:'7px 13px', borderRadius:99, fontSize:12.5, fontWeight:600,
      border:'1.5px solid '+(active?'var(--ink)':'var(--line)'), background: active?'var(--ink)':'var(--surface)', color: active?'var(--surface)':'var(--ink-2)', transition:'.14s' }}>
      {children}
    </button>
  );
}

Object.assign(window, { Catalogo, ProductCard, PriceLine, Chip, HIDDEN_STATI_CATALOGO });