/* ============================================================
   PDF SCHEDA PRODOTTO — anteprima stampabile
   ============================================================ */

function PdfModal({ product, withBattery, listino, onClose }) {
  const vp = useViewport();
  const p = product;
  const cat = CATEGORIE.find(c=>c.id===p.cat);
  const booking = PRENOTAZIONI.find(b=>b.prodId===p.id);
  const oggi = new Date().toLocaleDateString('it-IT', { day:'2-digit', month:'long', year:'numeric' });
  // battery economics
  const bt = (window.battFromProduct ? window.battFromProduct(p.attr) : parseBatt(p.attr && p.attr['Batteria']));
  const battPrice = bt ? (listino||LISTINO_BATTERIE_INIT)[battKey(bt.volt, bt.amp)] : null;
  const battSr = battPrice===SR || battPrice==null;
  const withBatt = withBattery && bt && !battSr;
  const listinoPrice = p.prezzoConsigliato;
  const totale = (listinoPrice||0) + (withBatt?battPrice:0);

  // Carica foto da R2 e le converte in data URL base64 (così la stampa le vede sempre)
  const [media, setMedia] = React.useState([]);
  const [photosLoading, setPhotosLoading] = React.useState(true);
  const [photosReady, setPhotosReady] = React.useState(false);

  // Misura l'altezza del CONTENUTO per capire quante pagine A4 servono.
  const contentRef = React.useRef(null);
  const rulerRef = React.useRef(null);   // elemento di calibrazione alto 297mm
  const [pageCount, setPageCount] = React.useState(1);
  const MARGIN_MM_RATIO = 20 / 297;      // margini 10mm sopra + 10mm sotto su 297mm

  React.useEffect(() => {
    const measure = () => {
      if (contentRef.current && rulerRef.current) {
        const h = contentRef.current.scrollHeight;
        // quanti px = 297mm REALI nel browser corrente (calibrazione)
        const pageHeightPx = rulerRef.current.offsetHeight || 1122;
        const usable = pageHeightPx * (1 - MARGIN_MM_RATIO); // pagina meno margini
        setPageCount(Math.max(1, Math.ceil(h / usable)));
      }
    };
    measure();
    const t1 = setTimeout(measure, 200);
    const t2 = setTimeout(measure, 500); // ri-misura dopo il render foto
    window.addEventListener('resize', measure);
    return () => { clearTimeout(t1); clearTimeout(t2); window.removeEventListener('resize', measure); };
  }, [media, photosReady, p]);

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const list = await window.DataAPI.list('product_media', { eq:['product_id', p.id] }) || [];
        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 (sorted.length === 0) {
          if (!cancelled) { setMedia([]); setPhotosLoading(false); setPhotosReady(true); }
          return;
        }
        // Converte ogni immagine in data URL base64 via canvas.
        // Necessario perché window.print() non renderizza in modo affidabile
        // le immagini remote (CORS/decoding). Le base64 sono embeddate nel DOM.
        const toDataUrl = (url) => new Promise((resolve) => {
          const img = new Image();
          img.crossOrigin = 'anonymous';
          img.onload = () => {
            const ratio = (img.naturalWidth && img.naturalHeight) ? img.naturalWidth/img.naturalHeight : null;
            try {
              const canvas = document.createElement('canvas');
              canvas.width = img.naturalWidth;
              canvas.height = img.naturalHeight;
              const ctx = canvas.getContext('2d');
              ctx.drawImage(img, 0, 0);
              resolve({ dataUrl: canvas.toDataURL('image/jpeg', 0.85), ratio });
            } catch (e) {
              resolve({ dataUrl: url, ratio }); // fallback all'URL originale
            }
          };
          img.onerror = () => resolve({ dataUrl: url, ratio: null });
          img.src = url;
        });

        const withData = await Promise.all(sorted.map(async m => {
          const r = await toDataUrl(m.url);
          return { ...m, dataUrl: r.dataUrl, ratio: r.ratio };
        }));

        if (!cancelled) {
          setMedia(withData);
          setPhotosLoading(false);
          setPhotosReady(true);
        }
      } catch(e) {
        if (!cancelled) { setPhotosLoading(false); setPhotosReady(true); }
      }
    })();
    return () => { cancelled = true; };
  }, [p.id]);

  const mainPhoto = media[0] || null;
  const galleryPhotos = media.slice(1, 5); // max 4 in gallery

  const handlePrint = () => {
    if (!photosReady) return;
    // Il nome del file PDF deriva dal titolo del documento.
    // Formato: "Nome Macchina - Matricola - Menabue Carrelli Elevatori"
    const nomeMacchina = `${p.marca||''} ${p.modello||''}`.trim() || p.nome || 'Scheda';
    const matr = p.matricola || p.id || '';
    const prevTitle = document.title;
    document.title = `${nomeMacchina}${matr?` - ${matr}`:''} - Menabue Carrelli Elevatori`;
    // Ripristina il titolo dopo la stampa
    const restore = () => { document.title = prevTitle; window.removeEventListener('afterprint', restore); };
    window.addEventListener('afterprint', restore);
    setTimeout(restore, 3000); // fallback se afterprint non scatta
    window.print();
  };

  const matrLabel = p.matricola || '—';

  return (
    <div className="pdf-overlay" style={{ position:'fixed', inset:0, zIndex:100, display:'flex', flexDirection:'column', alignItems:'center',
      background:'rgba(15,17,21,.62)', backdropFilter:'blur(4px)', animation:'fadeIn .15s ease', overflowY:'auto', padding: vp.isMobile?'14px 12px':'26px 24px' }} onClick={onClose}>
      {/* Ruler invisibile alto 297mm: serve a calibrare mm→px nel browser corrente */}
      <div ref={rulerRef} aria-hidden="true" style={{ position:'absolute', top:0, left:0, width:1, height:'297mm', visibility:'hidden', pointerEvents:'none' }} />
      {/* toolbar */}
      <div className="no-print" onClick={e=>e.stopPropagation()} style={{ width: vp.isMobile?'100%':'210mm', maxWidth:'100%',
        display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: vp.isMobile?12:16, gap:10, flexWrap: vp.isMobile?'wrap':'nowrap' }}>
        <div style={{ color:'#fff', minWidth:0, flex:1 }}>
          <div style={{ fontSize: vp.isMobile?13:15, fontWeight:800 }}>Anteprima PDF {!vp.isMobile && '— Scheda prodotto'}</div>
          <div style={{ fontSize: vp.isMobile?11.5:12.5, color:'rgba(255,255,255,.7)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
            {p.marca} {p.modello}{p.matricola ? ` · ${p.matricola}` : ''}
            {pageCount > 1 && <span style={{ marginLeft:8, color:'rgba(255,255,255,.9)', fontWeight:700 }}>· {pageCount} pagine</span>}
          </div>
        </div>
        <div style={{ display:'flex', gap:8, alignItems:'center', flexShrink:0 }}>
          {photosLoading && (
            <span style={{ fontSize:11.5, color:'rgba(255,255,255,.7)', display: vp.isMobile?'none':'inline' }}>Caricamento…</span>
          )}
          {!photosLoading && !photosReady && (
            <span style={{ fontSize:11.5, color:'rgba(255,255,255,.7)', display: vp.isMobile?'none':'inline' }}>Preparazione…</span>
          )}
          <Btn variant="ghost" size={vp.isMobile?'sm':'md'} onClick={onClose} style={{ background:'rgba(255,255,255,.1)', color:'#fff', boxShadow:'none' }}>
            {vp.isMobile ? <Icon name="x" size={15} /> : 'Chiudi'}
          </Btn>
          <Btn icon="download" size={vp.isMobile?'sm':'md'} onClick={handlePrint} disabled={!photosReady}>
            {vp.isMobile ? 'Stampa' : 'Stampa / Scarica'}
          </Btn>
        </div>
      </div>

      {/* A4 sheet — su mobile scalato per stare a video */}
      <div className="pdf-print" onClick={e=>e.stopPropagation()} style={{
        position:'relative', flexShrink:0,
        width:'210mm', maxWidth: vp.isMobile?'none':'100%',
        height: (pageCount * 297) + 'mm',   // fogli A4 impilati: il bianco copre tutte le pagine
        background:'#fff',
        boxShadow:'0 30px 80px rgba(0,0,0,.4)', padding:'0', animation:'floatIn .25s ease',
        transform: vp.isMobile ? 'scale('+Math.min(1, (window.innerWidth - 24) / (794))+')' : 'none',
        transformOrigin: 'top center',
        marginBottom: vp.isMobile ? -(297 * pageCount * 3.78 * (1 - Math.min(1, (window.innerWidth - 24) / (794)))) + 'px' : '0'
      }}>
        {/* Linee di separazione tra i fogli A4 (solo anteprima) — posizionate in mm */}
        {pageCount > 1 && Array.from({length: pageCount-1}).map((_,i) => (
          <div key={i} className="no-print" style={{ position:'absolute', left:0, right:0, top:(297*(i+1))+'mm', zIndex:5, pointerEvents:'none' }}>
            <div style={{ borderTop:'2px dashed rgba(200,16,46,.4)' }} />
            <div style={{ position:'absolute', right:14, top:-22, fontSize:11, fontWeight:800, color:'var(--red)',
              background:'#fff', padding:'2px 10px', borderRadius:99, border:'1px solid rgba(200,16,46,.35)' }}>
              segue → pag. {i+2}
            </div>
          </div>
        ))}

        {/* CONTENUTO — misurato per il calcolo pagine, con margini di sicurezza */}
        <div ref={contentRef}>
        {/* header band */}
        <div className="pdf-header-band" style={{ background:'#c8102e', color:'#fff', padding:'26px 34px', display:'flex', alignItems:'flex-start', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:28, fontWeight:800, letterSpacing:'-.01em', lineHeight:1, color:'#fff' }}>Menabue</div>
            <div style={{ fontSize:12, fontWeight:600, letterSpacing:'.02em', opacity:.9, marginTop:4, color:'#fff' }}>carrelli elevatori</div>
          </div>
          <div style={{ textAlign:'right' }}>
            <div style={{ fontSize:11, fontWeight:700, letterSpacing:'.08em', opacity:.85, color:'#fff' }}>SCHEDA PRODOTTO</div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:24, fontWeight:800, marginTop:2, color:'#fff' }}>{matrLabel}</div>
          </div>
        </div>

        <div style={{ padding:'30px 34px' }}>
          {/* title */}
          <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:20 }}>
            <div>
              <div style={{ fontSize:12, color:'var(--ink-3)', fontWeight:700, textTransform:'uppercase', letterSpacing:'.04em' }}>{cat.nome}{p.sub?` · ${p.sub}`:''}</div>
              <h1 style={{ margin:'4px 0 0', fontFamily:'var(--font-display)', fontSize:30, fontWeight:800, letterSpacing:'-.02em' }}>{p.marca} {p.modello}</h1>
            </div>
            <StatoBadge stato={p.stato} />
          </div>

          {/* images */}
          <PdfImages mainPhoto={mainPhoto} galleryPhotos={galleryPhotos} loading={photosLoading} />

          {/* Costi — blocco compatto in alto, non si spezza mai tra pagine */}
          <div className="pdf-no-break" style={{ marginBottom:26 }}>
            <PdfSectionTitle>Costi</PdfSectionTitle>
            {listinoPrice!=null ? (
              <div style={{ border:'1px solid var(--line)', borderRadius:10, overflow:'hidden', marginBottom:12, maxWidth:'62%' }}>
                <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13 }}>
                  <span style={{ color:'var(--ink-2)', fontWeight:600 }}>Costo macchina</span>
                  <span style={{ fontWeight:700 }}>{fmtEur(listinoPrice)}</span>
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', padding:'11px 15px', fontSize:13, borderTop:'1px solid var(--line-2)' }}>
                  <span style={{ color:'var(--ink-2)', fontWeight:600 }}>Costo batteria nuova</span>
                  <span style={{ fontWeight:700, color: withBatt?'var(--ink)':'var(--ink-4)' }}>{withBatt?fmtEur(battPrice):(bt&&battSr?'Su richiesta':'—')}</span>
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', padding:'13px 15px', background:'var(--surface-2)', borderTop:'1px solid var(--line)' }}>
                  <span style={{ fontWeight:800 }}>Costo totale</span>
                  <span style={{ fontFamily:'var(--font-display)', fontSize:22, fontWeight:800 }}>{fmtEur(totale)}</span>
                </div>
              </div>
            ) : (
              <div style={{ background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:10, padding:'16px 18px', marginBottom:12, maxWidth:'62%' }}>
                <div style={{ fontSize:11.5, color:'var(--ink-4)', fontWeight:700, textTransform:'uppercase', letterSpacing:'.04em' }}>Tariffa noleggio</div>
                <div style={{ fontFamily:'var(--font-display)', fontSize:24, fontWeight:800, letterSpacing:'-.02em', marginTop:2 }}>{fmtEur(p.prezzoGiorno)} /g · {fmtEur(p.prezzoMese)} /m</div>
              </div>
            )}
            <div style={{ display:'flex', gap:24, flexWrap:'wrap', alignItems:'center', fontSize:12 }}>
              <span style={{ color:'var(--ink-3)', fontWeight:600, display:'flex', alignItems:'center', gap:6 }}>
                <Icon name="pin" size={12} /> Prezzi IVA esclusa — trasporto escluso
              </span>
              <span style={{ color:'var(--ink-3)', fontWeight:600 }}>Stato: <b style={{ color:'var(--ink)' }}>{STATI[p.stato].label}</b></span>
              <span style={{ color:'var(--ink-3)', fontWeight:600 }}>Matricola: <b style={{ color:'var(--ink)' }}>{matrLabel}</b></span>
              {booking && <span style={{ color:'var(--ink-3)', fontWeight:600 }}>Riferimento: <b style={{ color:'var(--ink)' }}>{booking.cliente}</b></span>}
            </div>
          </div>

          {/* Dati tecnici — a piena larghezza in 2 colonne, LIBERI di fluire su più pagine */}
          <PdfSectionTitle>Dati tecnici</PdfSectionTitle>
          <div style={{ columnCount:2, columnGap:34 }}>
            {Object.entries(p.attr).map(([k,v]) => (
              <div key={k} className="pdf-attr-row" style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:'1px solid var(--line-2)', fontSize:13, breakInside:'avoid' }}>
                <span style={{ color:'var(--ink-3)', fontWeight:600 }}>{k}</span>
                <span style={{ fontWeight:700, textAlign:'right' }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* footer */}
        <div style={{ padding:'16px 34px', borderTop:'1px solid var(--line)', display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--ink-3)' }}>
          <span>smartfleet-menabue.com — Documento riservato</span>
          <span>Generato il {oggi}</span>
        </div>
        </div>{/* /contentRef */}
      </div>
      <div style={{ height:60, flexShrink:0 }} className="no-print" />
    </div>
  );
}

/* Layout immagini del PDF: 1 grande a sinistra + griglia 2x2 a destra */
function PdfImages({ mainPhoto, galleryPhotos, loading }) {
  if (loading) {
    return (
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gap:10, marginBottom:24 }}>
        <div style={{ gridRow:'span 2', height:210, background:'var(--surface-2)', borderRadius:8 }} />
        {Array.from({length:4}).map((_,i)=>(
          <div key={i} style={{ height:100, background:'var(--surface-2)', borderRadius:8 }} />
        ))}
      </div>
    );
  }
  if (!mainPhoto) {
    return (
      <div style={{ height:210, background:'var(--surface-2)', borderRadius:8, marginBottom:24,
        display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-4)', fontWeight:600, fontSize:14, border:'1px solid var(--line)' }}>
        Nessuna foto disponibile
      </div>
    );
  }
  // Solo la foto di copertina, larga metà foglio e centrata
  const mainSrc = mainPhoto.dataUrl || mainPhoto.url;
  const mainIsStd = mainPhoto.ratio == null || Math.abs(mainPhoto.ratio - 1350/1080) < 0.06;
  return (
    <div style={{ display:'flex', justifyContent:'center', marginBottom:24 }}>
      {/* Foto copertina: metà larghezza foglio, proporzioni 5:4 (1350×1080) */}
      <div style={{ position:'relative', width:'50%', paddingBottom:'40%', borderRadius:8, overflow:'hidden', background:'#eef0f4',
        backgroundImage: mainIsStd ? 'none' : `url("${mainSrc}")`, backgroundSize:'cover', backgroundPosition:'center' }}>
        {!mainIsStd && <div style={{ position:'absolute', inset:0, background:'rgba(238,240,244,.5)' }} />}
        <img src={mainSrc} alt=""
          style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit: mainIsStd?'cover':'contain', display:'block' }} />
      </div>
    </div>
  );
}

function PdfSectionTitle({ children }) {
  return (
    <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:10 }}>
      <span style={{ width:4, height:16, borderRadius:2, background:'var(--red)' }} />
      <span style={{ fontFamily:'var(--font-display)', fontSize:14, fontWeight:800, textTransform:'uppercase', letterSpacing:'.04em' }}>{children}</span>
    </div>
  );
}
function PdfRow({ label, value }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:'1px solid var(--line-2)', fontSize:13 }}>
      <span style={{ color:'var(--ink-3)', fontWeight:600 }}>{label}</span>
      <span style={{ fontWeight:700, textAlign:'right' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { PdfModal });