/* ============================================================
   SCHEDA PRODOTTO — galleria, prezzi per ruolo, sim batteria, PDF
   ============================================================ */

/* Ricava {volt, amp} dagli attributi del prodotto.
   Formato NUOVO (editor WordPress): attributi separati "Voltaggio" + "Amperaggio".
   Formato VECCHIO (mock): unico attributo "Batteria" = "48V / 500Ah".
   Normalizza al formato del listino batterie (es. "80V" | "620Ah"). */
function battFromProduct(attr) {
  if (!attr) return null;
  // 1) Formato nuovo: due campi separati
  let volt = attr['Voltaggio'] || attr['voltaggio'] || null;
  let amp  = attr['Amperaggio'] || attr['amperaggio'] || null;
  if (volt && amp) {
    // normalizza: assicura la "V" e "Ah" finali come nel listino
    volt = String(volt).trim();
    amp  = String(amp).trim();
    if (!/v$/i.test(volt)) volt = volt + 'V';
    if (!/ah$/i.test(amp)) amp = amp + 'Ah';
    // normalizza casi speciali del listino
    volt = volt.replace(/^2\s*x\s*40V$/i, '2 x 40V').replace(/^2x12V$/i, '2x12V');
    return { volt, amp };
  }
  // 2) Fallback formato vecchio combinato
  if (attr['Batteria'] && typeof parseBatt === 'function') {
    return parseBatt(attr['Batteria']);
  }
  return null;
}
window.battFromProduct = battFromProduct;

function InfoRow({ label, value, strong }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:16, padding:'11px 0', borderBottom:'1px solid var(--line-2)' }}>
      <span style={{ fontSize:13, color:'var(--ink-3)', fontWeight:600 }}>{label}</span>
      <span style={{ fontSize:13.5, fontWeight: strong?800:600, color:'var(--ink)', textAlign:'right' }}>{value}</span>
    </div>
  );
}

function BatterySim({ p, listino, on, setOn }) {
  const bt = battFromProduct(p.attr);
  if (!bt) return null;
  const price = (listino || LISTINO_BATTERIE_INIT)[battKey(bt.volt, bt.amp)];
  const base = p.prezzoConsigliato || 0;
  const sr = price === SR || price == null;
  return (
    <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', padding:'18px 20px', boxShadow:'var(--sh-1)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
        <span style={{ width:34, height:34, borderRadius:9, background:'var(--red-tint)', color:'var(--red)', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="battery" size={19} />
        </span>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:800 }}>Simulazione batteria nuova</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>Listino · {bt.volt} — {bt.amp}</div>
        </div>
      </div>
      {sr ? (
        <div style={{ fontSize:13, color:'var(--ink-3)', padding:'10px 13px', background:'var(--surface-2)', borderRadius:'var(--r-md)', fontWeight:600 }}>
          Prezzo batteria <b>su richiesta</b> per questa configurazione.
        </div>
      ) : (
        <>
          <label onClick={()=>setOn(v=>!v)} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', cursor:'pointer', marginBottom:on?14:0 }}>
            <span style={{ fontSize:13.5, fontWeight:600, color:'var(--ink-2)' }}>Includi batteria nuova (+{fmtEur(price)})</span>
            <span style={{ width:44, height:25, borderRadius:99, background:on?'var(--red)':'var(--line)', position:'relative', transition:'.2s', flexShrink:0 }}>
              <span style={{ position:'absolute', top:3, left:on?22:3, width:19, height:19, borderRadius:99, background:'#fff', transition:'.2s', boxShadow:'0 1px 3px rgba(0,0,0,.2)' }} />
            </span>
          </label>
          {on && (
            <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', padding:'12px 14px', background:'var(--red-tint)', borderRadius:'var(--r-md)', animation:'scaleIn .2s ease' }}>
              <span style={{ fontSize:13, fontWeight:700, color:'var(--red)' }}>Prezzo indicativo</span>
              <span style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:800, color:'var(--red)' }}>{fmtEur(base + price)}</span>
            </div>
          )}
        </>
      )}
    </div>
  );
}

/* ---- Card noleggio in corso (per stato NOLEGGIATO) ------- */
function NoleggioCorsoCard({ archive, productId }) {
  const noleggio = (archive||[])
    .filter(b => b.prodId === productId && b.esito === 'confermata' && (b.tipo === 'STR' || b.tipo === 'LTR') && !b.rientrato)
    .sort((a,b) => new Date(b.chiusoIl||0) - new Date(a.chiusoIl||0))[0];
  if (!noleggio) return null;
  const dataRientro = noleggio.dataRientro || noleggio.data_rientro || noleggio.fine;
  const dataConsegna = noleggio.dataConsegna || noleggio.data_consegna || noleggio.inizio;
  const dl = dataRientro ? Math.ceil((new Date(dataRientro) - new Date())/(1000*60*60*24)) : null;
  let badgeColor = 'var(--st-disponibile)', badgeBg = '#e8f6f0', badgeLabel = '—';
  if (dl !== null) {
    if (dl < 0) { badgeColor = 'var(--red)'; badgeBg = 'var(--red-tint)'; badgeLabel = `rientrato da ${-dl} gg`; }
    else if (dl === 0) { badgeColor = 'var(--red)'; badgeBg = 'var(--red-tint)'; badgeLabel = 'rientra oggi'; }
    else if (dl <= 7) { badgeColor = 'var(--st-prenotato)'; badgeBg = '#fdf0e0'; badgeLabel = `tra ${dl} gg`; }
    else { badgeLabel = `tra ${dl} gg`; }
  }
  return (
    <div style={{ background:'var(--surface)', border:'1.5px solid #6c5ce7', borderRadius:'var(--r-lg)', padding:'16px 20px', boxShadow:'var(--sh-1)', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', top:0, left:0, width:4, height:'100%', background:'#6c5ce7' }} />
      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
        <span style={{ width:34, height:34, borderRadius:9, background:'#ede9fe', color:'#6c5ce7', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="clock" size={19} />
        </span>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:800 }}>Noleggio in corso</div>
          <div style={{ fontSize:12, color:'var(--ink-3)' }}>{noleggio.tipo} · {noleggio.cliente}</div>
        </div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:10 }}>
        <div style={{ padding:'10px 12px', background:'var(--surface-2)', borderRadius:'var(--r-md)' }}>
          <div style={{ fontSize:11, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.03em' }}>Consegna</div>
          <div style={{ fontSize:13.5, fontWeight:700, marginTop:2 }}>{dataConsegna ? fmtDate(new Date(dataConsegna)) : '—'}</div>
        </div>
        <div style={{ padding:'10px 12px', background:'var(--surface-2)', borderRadius:'var(--r-md)' }}>
          <div style={{ fontSize:11, fontWeight:700, color:'var(--ink-4)', textTransform:'uppercase', letterSpacing:'.03em' }}>Rientro</div>
          <div style={{ fontSize:13.5, fontWeight:700, marginTop:2 }}>{dataRientro ? fmtDate(new Date(dataRientro)) : '—'}</div>
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'8px 13px', background: badgeBg, borderRadius:'var(--r-md)' }}>
        <span style={{ fontSize:12.5, fontWeight:700, color: badgeColor }}>Rientro previsto</span>
        <span style={{ fontSize:12.5, fontWeight:800, color: badgeColor }}>{badgeLabel}</span>
      </div>
      <div style={{ marginTop:10, fontSize:11.5, color:'var(--ink-4)' }}>
        Commerciale: <b style={{ color:'var(--ink-2)' }}>{noleggio.commerciale}</b>
      </div>
    </div>
  );
}

function ProductDetail({ p, role, back, onPrenota, onPDF, listino, onStr, onStorico, archive, toast, attributi }) {
  const vp = useViewport();
  const [watched, setWatched] = useState(false);
  const [watchBusy, setWatchBusy] = useState(false);
  const [showMin, setShowMin] = useState(false);
  const [battOn, setBattOn] = useState(false);
  const cat = CATEGORIE.find(c=>c.id===p.cat);
  // Nomi degli attributi marcati "sede" → mostrati nella sezione ubicazione, non nella scheda tecnica
  const sedeNames = (attributi||[]).filter(a=>a.sede).map(a=>a.nome);
  const sedeValues = sedeNames.map(n => p.attr && p.attr[n] ? { nome:n, val:p.attr[n] } : null).filter(Boolean);
  const isNoleggio = p.prezzoConsigliato==null && p.prezzoGiorno!=null;
  const canBook = !['VENDUTO','ARCHIVIATO','NOLEGGIATO','IN_ARRIVO'].includes(p.stato);
  const hasMin = p.prezzoMinimo!=null;
  const isNoleggiato = p.stato === 'NOLEGGIATO';

  // Carica lo stato iniziale watched
  useEffect(() => {
    let cancelled = false;
    (async () => {
      const isW = await window.WatchAPI?.isWatching?.(p.id);
      if (!cancelled) setWatched(!!isW);
    })();
    return () => { cancelled = true; };
  }, [p.id]);

  const handleToggleWatch = async () => {
    if (watchBusy) return;
    setWatchBusy(true);
    const result = await window.WatchAPI?.toggleWatch?.(p.id);
    setWatchBusy(false);
    if (!result?.ok) {
      toast?.('Errore aggiornamento tieni d\'occhio');
      return;
    }
    setWatched(result.watching);
    toast?.(result.watching ? 'Aggiunto ai mezzi tenuti d\'occhio' : 'Rimosso dai mezzi tenuti d\'occhio');
  };

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden' }}>
      {/* breadcrumb */}
      <div style={{ padding: vp.isMobile?'12px 14px':'16px 30px', borderBottom:'1px solid var(--line)', background:'var(--surface)', display:'flex', alignItems:'center', gap:10 }}>
        <button onClick={back} style={{ display:'flex', alignItems:'center', gap:7, fontSize:13, fontWeight:700, color:'var(--ink-2)', padding:'7px 12px', borderRadius:'var(--r-md)', border:'1.5px solid var(--line)' }}>
          <Icon name="chevLeft" size={16} /> {vp.isMobile ? '' : 'Catalogo'}
        </button>
        <div style={{ fontSize:12.5, color:'var(--ink-4)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
          <span style={{ color:'var(--ink-3)', fontWeight:600 }}>{cat.nome}</span>
          {p.sub && <> · {p.sub}</>}
        </div>
      </div>

      <div style={{ padding: vp.isMobile?'16px 12px 30px':'26px 30px 50px',
        display:'grid',
        gridTemplateColumns: vp.isMobile?'1fr':(vp.isTablet?'1fr':'1.5fr 1fr'),
        gap: vp.isMobile?18:30, maxWidth:1280, margin:'0 auto' }}>
        {/* LEFT — gallery + tech */}
        <div>
          {/* gallery */}
          <ProductGallery productId={p.id} />

          {/* technical data */}
          <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', padding: vp.isMobile?'18px 16px':'22px 24px', boxShadow:'var(--sh-1)' }}>
            <h3 style={{ margin:'0 0 6px', fontFamily:'var(--font-display)', fontSize: vp.isMobile?15.5:17, fontWeight:800 }}>Dati tecnici</h3>
            <p style={{ margin:'0 0 12px', fontSize:12.5, color:'var(--ink-3)' }}>Attributi attivi per la categoria <b>{cat.nome}</b></p>
            <div style={{ display:'grid', gridTemplateColumns: vp.isMobile?'1fr':'1fr 1fr', gap:'0 32px' }}>
              {Object.entries(p.attr).filter(([k])=>!sedeNames.includes(k)).map(([k,v]) => <InfoRow key={k} label={k} value={v} />)}
            </div>
          </div>
        </div>

        {/* RIGHT — summary + price + actions */}
        <div style={{ display:'flex', flexDirection:'column', gap: vp.isMobile?14:18 }}>
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
              <StatoBadge stato={p.stato} />
              {p.nuovo && <span style={{ fontSize:10.5, fontWeight:800, letterSpacing:'.06em', color:'#fff', background:'var(--red)', padding:'3px 9px', borderRadius:99 }}>NUOVO</span>}
              <span style={{ fontFamily:'var(--font-display)', fontSize:13, fontWeight:800, color:'var(--ink-3)', marginLeft:'auto' }}>{prodMatricola(p)}</span>
            </div>
            <h1 style={{ margin:'0 0 6px', fontFamily:'var(--font-display)', fontSize:30, fontWeight:800, letterSpacing:'-.02em', lineHeight:1.05 }}>{prodLabel(p)}</h1>
            {sedeValues.length>0 ? (
              <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
                {sedeValues.map(s => (
                  <div key={s.nome} style={{ display:'flex', alignItems:'center', gap:6, fontSize:13.5, color:'var(--ink-3)' }}>
                    <Icon name="pin" size={15} /> {s.val}
                  </div>
                ))}
              </div>
            ) : p.posizione ? (
              <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:13.5, color:'var(--ink-3)' }}>
                <Icon name="pin" size={15} /> {p.posizione}
              </div>
            ) : null}
          </div>

          {/* Card noleggio in corso — solo se NOLEGGIATO */}
          {isNoleggiato && <NoleggioCorsoCard archive={archive} productId={prodMatricola(p)} />}

          {/* price card */}
          <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', padding:'20px 22px', boxShadow:'var(--sh-1)' }}>
            {isNoleggio ? (
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
                <PriceBox label="Giornaliero" value={fmtEur(p.prezzoGiorno)} />
                <PriceBox label="Mensile" value={fmtEur(p.prezzoMese)} />
              </div>
            ) : (
              <>
                <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
                  <div>
                    <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:3 }}>
                      <span style={{ fontSize:12, color: showMin?'var(--red)':'var(--ink-4)', fontWeight:700, textTransform:'uppercase', letterSpacing:'.04em' }}>{showMin?'Prezzo minimo autorizzato':'Prezzo di listino'}</span>
                      {hasMin && (
                        <button onClick={()=>setShowMin(s=>!s)} title={showMin?'Mostra prezzo di listino':'Mostra prezzo minimo (riservato)'}
                          style={{ display:'flex', alignItems:'center', color: showMin?'var(--red)':'var(--ink-4)', opacity: showMin?1:.45, transition:'.15s', padding:2 }}
                          onMouseEnter={e=>e.currentTarget.style.opacity=1} onMouseLeave={e=>e.currentTarget.style.opacity=showMin?1:.45}>
                          <Icon name={showMin?'eyeOff':'eye'} size={15} />
                        </button>
                      )}
                    </div>
                    <div style={{ fontFamily:'var(--font-display)', fontSize:32, fontWeight:800, letterSpacing:'-.02em', color: showMin?'var(--red)':'var(--ink)' }}>{fmtEur(showMin?p.prezzoMinimo:p.prezzoConsigliato)}</div>
                  </div>
                  <span style={{ fontSize:11.5, fontWeight:700, color:'var(--ink-3)', background:'var(--line-2)', padding:'4px 10px', borderRadius:99 }}>{(p.liste||[p.dest]).join(' · ')}</span>
                </div>
                {p.prezzoGiorno!=null && (
                  <div style={{ marginTop:12, paddingTop:12, borderTop:'1px dashed var(--line)', display:'flex', justifyContent:'space-between', fontSize:12.5, color:'var(--ink-3)' }}>
                    <span>Anche a noleggio</span><span style={{ fontWeight:700, color:'var(--ink-2)' }}>{fmtEur(p.prezzoGiorno)}/g · {fmtEur(p.prezzoMese)}/m</span>
                  </div>
                )}
              </>
            )}
          </div>

          {/* actions */}
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            <Btn size="lg" full icon="calendar" onClick={()=>onPrenota(p)} disabled={!canBook}>
              {canBook ? 'Prenota questo mezzo' : 'Non prenotabile'}
            </Btn>
            <div style={{ display:'flex', gap:10 }}>
              <Btn variant="ghost" full icon="pdf" onClick={()=>onPDF(p, { withBattery: battOn })}>Genera PDF</Btn>
              <Btn variant={watched?'soft':'ghost'} full icon={watched?'starFilled':'star'} onClick={handleToggleWatch} disabled={watchBusy}>
                {watched?'Seguito':'Tieni d\u2019occhio'}
              </Btn>
            </div>
            <Btn variant="subtle" full icon="clock" onClick={onStr}>Listino STR — noleggio breve</Btn>
            <Btn variant="ghost" full icon="log" onClick={()=>onStorico(p)}>Storico macchina</Btn>
          </div>

          <BatterySim p={p} listino={listino} on={battOn} setOn={setBattOn} />

          {/* summary */}
          <div style={{ background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', padding:'6px 20px 14px', boxShadow:'var(--sh-1)' }}>
            <InfoRow label="Matricola" value={prodMatricola(p)} />
            <InfoRow label="Categoria" value={cat.nome} />
            {p.sub && <InfoRow label="Sottocategoria" value={p.sub} />}
            <InfoRow label={(p.liste||[p.dest]).length>1?'Liste':'Lista'} value={(p.liste||[p.dest]).join(' · ')} />
            <InfoRow label="Stato commerciale" value={STATI[p.stato].label} strong />
          </div>
        </div>
      </div>
    </div>
  );
}

function PriceBox({ label, value }) {
  return (
    <div style={{ background:'var(--surface-2)', borderRadius:'var(--r-md)', padding:'13px 15px' }}>
      <div style={{ fontSize:11.5, color:'var(--ink-4)', fontWeight:700, textTransform:'uppercase', letterSpacing:'.04em' }}>{label}</div>
      <div style={{ fontFamily:'var(--font-display)', fontSize:23, fontWeight:800, marginTop:2 }}>{value}</div>
    </div>
  );
}

/* ============================================================
   ProductGallery — galleria foto prodotto con miniature cliccabili
   ============================================================ */
function ProductGallery({ productId }) {
  const [media, setMedia] = useState([]);
  const [selectedIdx, setSelectedIdx] = useState(0);
  const [loading, setLoading] = useState(true);
  const [isStd, setIsStd] = useState(true); // formato ~5:4?

  const onMainLoad = (e) => {
    const img = e.target;
    if (img.naturalWidth && img.naturalHeight) {
      const ratio = img.naturalWidth / img.naturalHeight;
      setIsStd(Math.abs(ratio - 1350/1080) < 0.06);
    }
  };

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const list = await window.DataAPI.list('product_media', { eq:['product_id', productId] }) || [];
        const sorted = list.slice().sort((a,b) => {
          if (a.is_main && !b.is_main) return -1;
          if (!a.is_main && b.is_main) return 1;
          return (a.ordine||0) - (b.ordine||0);
        });
        if (!cancelled) {
          setMedia(sorted);
          setSelectedIdx(0);
        }
      } catch(e) { console.error('ProductGallery load product_media:', e?.message || e, e); }
      finally { if (!cancelled) setLoading(false); }
    })();
    return () => { cancelled = true; };
  }, [productId]);

  const selected = media[selectedIdx];
  if (loading) {
    return <div style={{ width:'100%', height:380, marginBottom:12, background:'var(--line-2)', borderRadius:14 }} />;
  }
  if (media.length === 0) {
    return (
      <div style={{ width:'100%', height:380, marginBottom:30, background:'var(--line-2)', borderRadius:14,
        display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-4)', fontSize:14, fontWeight:600 }}>
        Nessuna foto disponibile
      </div>
    );
  }
  return (
    <>
      <div style={{ position:'relative', width:'100%', height:380, marginBottom:12, background:'var(--surface-2)', borderRadius:14, overflow:'hidden',
        display:'flex', alignItems:'center', justifyContent:'center' }}>
        {/* Sfondo sfocato solo se la foto NON è nel formato standard 5:4 */}
        {!isStd && (
          <img src={selected.url} alt="" aria-hidden="true" style={{ position:'absolute', inset:0, width:'100%', height:'100%',
            objectFit:'cover', filter:'blur(22px) brightness(.75)', transform:'scale(1.15)', opacity:.85 }} />
        )}
        <img src={selected.url} alt="" onLoad={onMainLoad}
          style={{ position:'relative', width: isStd?'100%':'auto', height: isStd?'100%':'auto',
            maxWidth:'100%', maxHeight:'100%', objectFit: isStd?'cover':'contain', display:'block', zIndex:1 }} />
      </div>
      {media.length > 1 && (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:12, marginBottom:30 }}>
          {media.slice(0, 8).map((m, i) => (
            <button key={m.id} onClick={()=>setSelectedIdx(i)} style={{
              width:'100%', height:76, padding:0, borderRadius:10, overflow:'hidden',
              border:'2px solid '+(i===selectedIdx?'var(--red)':'transparent'), cursor:'pointer' }}>
              <img src={m.url} alt="" style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
            </button>
          ))}
        </div>
      )}
    </>
  );
}

Object.assign(window, { ProductDetail, BatterySim, InfoRow, PriceBox, NoleggioCorsoCard, ProductGallery });