/* PORCEVILLE — Catálogo de produtos + Detalhe (qtd + cores da logo) */

function PorceProductCard({ product, app }) {
  return (
    <button className="card pop-in" onClick={() => app.openDetail(product.id)}
      style={{ border: 'none', textAlign: 'left', cursor: 'pointer', overflow: 'hidden', padding: 0, width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ position: 'relative', background: '#fff' }}>
        <PPhoto kind={product.kind} illo={PORCE_ILLO.illoFor(product)} img={product.img} slot={`pcat-${product.id}`} placeholder="Foto" fit="cover" style={{ width: '100%', aspectRatio: '1 / 1' }} />
        {product.best && <span className="chip-gold" style={{ position: 'absolute', top: 10, left: 10, fontSize: 10.5, padding: '4px 9px', borderRadius: 8 }}>★ Mais pedido</span>}
        {product.ready && <span className="chip-soft" style={{ position: 'absolute', top: 10, left: 10, fontSize: 10.5, padding: '4px 9px', borderRadius: 8 }}>Pronta entrega</span>}
      </div>
      <div style={{ padding: '12px 13px 13px', display: 'flex', flexDirection: 'column', flex: 1, width: '100%' }}>
        <div className="display" style={{ fontSize: 16, color: 'var(--navy)', lineHeight: 1.18, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', minHeight: '2.4em' }}>{displayName(product.name)}</div>
        <div className="muted" style={{ fontSize: 11.5, marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{(product.sizes && product.sizes.length) ? `${product.sizes.join('/')} ${product.unit || 'ml'}${product.detail ? ' · ' + product.detail : ''}` : (product.detail || '\u00a0')}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto', paddingTop: 10, width: '100%' }}>
          <span className="quote-tag" style={{ fontSize: 12.5 }}>{priceTag(product)}</span>
          <span style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--navy)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
            <PIcon name="plus" size={18} stroke="#fff" />
          </span>
        </div>
      </div>
    </button>
  );
}

function MobileBanner({ b }) {
  return (
    <button onClick={b.onClick} className="pop-in" style={{ gridColumn: '1 / -1', position: 'relative', border: 'none', cursor: 'pointer', borderRadius: 'var(--r-lg)', overflow: 'hidden', minHeight: 130, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '18px 18px', textAlign: 'left' }}>
      <div style={{ position: 'absolute', inset: 0, zIndex: 0 }}>
        {b.image
          ? <img src={b.image} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <PPhoto kind={b.kind} slot={b.slot} placeholder=" " style={{ width: '100%', height: '100%' }} />}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(90deg, rgba(13,43,90,.9) 0%, rgba(13,43,90,.62) 55%, rgba(13,43,90,.2) 100%)' }} />
      </div>
      <div style={{ position: 'relative', zIndex: 2 }}>
        <div style={{ fontSize: 10, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--gold)', fontWeight: 800 }}>{b.eyebrow}</div>
        <div className="display" style={{ fontSize: 21, color: '#fff', margin: '6px 0 12px', lineHeight: 1.12 }}>{b.title}</div>
        <span className="btn btn-gold btn-sm" style={{ pointerEvents: 'none' }}>{b.cta}</span>
      </div>
    </button>
  );
}

function PorceProductsScreen({ app }) {
  const [cat, setCat] = React.useState(app.productsCat || 'todos');
  const [busca, setBusca] = React.useState('');
  React.useEffect(() => { setCat(app.productsCat || 'todos'); }, [app.productsCat]);
  const norm = t => String(t || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  const base = cat === 'todos' ? PORCE_DATA.products : PORCE_DATA.products.filter(p => p.cat === cat);
  const list = busca.trim().length >= 2 ? base.filter(p => norm(p.name + ' ' + (p.detail || '')).includes(norm(busca))) : base;

  return (
    <div className="scroll" style={{ paddingBottom: 28 }}>
      <div style={{ paddingTop: 58, background: 'var(--porc-bg)', position: 'sticky', top: 0, zIndex: 30 }}>
        <div style={{ padding: '4px 18px' }}>
          <div className="eyebrow">Catálogo</div>
          <div className="h1" style={{ marginTop: 4 }}>Produtos</div>
        </div>
        <div style={{ padding: '10px 18px 0' }}>
          <input value={busca} onChange={e => setBusca(e.target.value)} placeholder="🔍 Buscar produto…" aria-label="Buscar produto"
            style={{ width: '100%', boxSizing: 'border-box', padding: '11px 15px', borderRadius: 99, border: '1.5px solid var(--line)', fontSize: 14.5, background: 'var(--surface)', outline: 'none' }} />
        </div>
        <div style={{ display: 'flex', flexWrap: 'nowrap', gap: 8, padding: '12px 18px 14px', overflowX: 'auto', WebkitOverflowScrolling: 'touch', scrollbarWidth: 'none' }}>
          {PORCE_DATA.categories.map(c => (
            <button key={c.id} className={`chip ${cat === c.id ? 'active' : ''}`} onClick={() => setCat(c.id)} style={{ padding: '9px 14px', flex: 'none' }}>
              <PIcon name={c.icon} size={15} stroke={cat === c.id ? '#fff' : 'var(--ink-soft)'} />
              {c.label}
            </button>
          ))}
        </div>
      </div>

      {/* banner técnica */}
      <div style={{ margin: '2px 18px 16px', borderRadius: 'var(--r-lg)', background: 'var(--navy)', padding: '16px 18px', display: 'flex', gap: 14, alignItems: 'center' }}>
        <PIcon name="palette" size={28} stroke="var(--gold)" />
        <div style={{ flex: 1 }}>
          <div className="display" style={{ color: '#fff', fontSize: 16.5 }}>Como funciona a gravação?</div>
          <div style={{ color: 'rgba(255,255,255,.75)', fontSize: 12.5, marginTop: 3, lineHeight: 1.45 }}>
            Logo em 1–5 cores (serigrafia, mín. {PORCE_DATA.MIN_SERI} un) ou Multicor total (sublimação, a partir de 1 peça).
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, padding: '0 18px' }}>
        {(() => {
          // banners do catálogo: editáveis no admin (site_content.mobile_banners); fallback = semente
          const mbDefault = [
            { pos: 3, kind: 'navy', image: 'uploads/banner/banner-corporativo.jpg', eyebrow: 'Brindes corporativos', title: 'Sua marca em cada detalhe', cta: 'Ver kits', cat_id: 'kits' },
            { pos: 7, kind: 'chopp', eyebrow: 'Linha cervejeira', title: 'Canecos & copos de chopp', cta: 'Ver chopp', cat_id: 'chopp' },
            { pos: 11, kind: 'sublime', eyebrow: 'Sublimação', title: 'A partir de 1 peça', cta: 'Ver canecas', cat_id: 'canecas' },
          ];
          const mbCfg = (PORCE_DATA.content && Array.isArray(PORCE_DATA.content.mobile_banners) && PORCE_DATA.content.mobile_banners.length)
            ? PORCE_DATA.content.mobile_banners : mbDefault;
          const banners = {};
          mbCfg.forEach((b, idx) => {
            if (!b || !(b.title || b.image)) return;
            let pos = Math.max(0, Math.round(Number(b.pos)));
            if (!Number.isFinite(pos)) pos = idx * 4 + 3;
            while (banners[pos]) pos++;   // posição duplicada não engole banner — empurra pro próximo slot
            banners[pos] = { ...b, slot: 'mbnr-' + idx, onClick: () => setCat(b.cat_id || 'todos') };
          });
          const out = [];
          list.forEach((p, i) => {
            out.push(<PorceProductCard key={p.id} product={p} app={app} />);
            if (cat === 'todos' && banners[i]) out.push(<MobileBanner key={'mb' + i} b={banners[i]} />);
          });
          return out;
        })()}
      </div>

      {/* não achou? captura de lead (mesma da home desktop) */}
      <div style={{ margin: '26px 18px 8px', background: 'linear-gradient(160deg, #16335F 0%, #101F3C 100%)', borderRadius: 'var(--r-lg)', padding: '22px 18px' }}>
        <HomeLeadForm dark />
      </div>
    </div>
  );
}

// ============ Detalhe do produto — adicionar ao orçamento ============
function PorceProductDetail({ app }) {
  const product = PORCE_DATA.getProduct(app.detailId);
  const isReady = !!product.ready;
  const MIN = PORCE_DATA.MIN_SERI;
  const pieceOpts = PORCE_DATA.pieceColorsFor(product);
  const hasPiece = pieceOpts.length > 0;
  const sizeOpts = product.sizes || null;
  const hasSize = !isReady && !!sizeOpts;

  // etapas do passo a passo: Tamanho → Cor da peça → Quantidade → Cor da logo
  const steps = isReady ? ['qty'] : [
    ...(hasSize ? ['size'] : []),
    ...(hasPiece ? ['piece'] : []),
    'qty', 'logo',
  ];
  const stepMeta = { size: 'Tamanho', piece: 'Cor da peça', logo: 'Cor da logo', qty: 'Quantidade' };

  const gallery = (product.images && product.images.length > 1) ? product.images : null;
  const colorVariants = (product.colors && product.colors.length > 1) ? product.colors : null;
  // rótulo da variação: novo formato {id} resolve via piece_colors; legado usa {name}
  const variantLabel = (c) => c.name || ((PORCE_DATA.pieceColors.find(pc => pc.id === c.id) || {}).label) || c.id || '';
  const [mainImg, setMainImg] = React.useState(product.img);
  const [activeVariant, setActiveVariant] = React.useState(colorVariants ? 0 : null);
  const [step, setStep] = React.useState(0);
  const [maxStep, setMaxStep] = React.useState(0); // etapa mais avançada já visitada — o recap só cita o que o usuário já viu
  const [qty, setQty] = React.useState(isReady ? 10 : 1);
  const [logo, setLogo] = React.useState(isReady ? null : 'colorido');
  const [piece, setPiece] = React.useState(hasPiece ? pieceOpts[0].id : null);
  const [size, setSize] = React.useState(hasSize ? (sizeOpts.includes(300) ? 300 : sizeOpts[0]) : null);
  const [autoSwitched, setAutoSwitched] = React.useState(false); // logo trocada automaticamente p/ Multicor (qtd < mínimo)
  const [addedSug, setAddedSug] = React.useState({});            // sugestões (kit/complementares) já adicionadas

  const isSeri = logo && logo !== 'colorido';
  const minQty = 1;                                // quantidade livre a partir de 1; serigrafia é travada pela disponibilidade das cores
  // cores da logo: Multicor sempre; 1–5 cores (serigrafia) aparecem sempre que o produto aceita, desabilitadas abaixo do mínimo
  const logoOpts = PORCE_DATA.logoColors.filter(o => o.id === 'colorido' ? true : !!product.seri);
  const seriEnabled = !!product.seri && qty >= MIN;

  // auto-seleciona a cor da logo pela regra (qtd < mínimo → Multicor) e sinaliza quando a troca for automática
  React.useEffect(() => {
    if (isReady) return;
    if (qty < MIN && logo && logo !== 'colorido') { setLogo('colorido'); setAutoSwitched(true); }
    else if (!logo) setLogo((product.seri && qty >= MIN) ? '1' : 'colorido');
    else if (qty >= MIN) setAutoSwitched(false);
  }, [qty]);

  const cur = steps[step];
  const isLast = step === steps.length - 1;
  const stepValid = cur === 'qty' ? qty >= minQty : cur === 'logo' ? !!logo : true;
  const visited = (s) => { const i = steps.indexOf(s); return i > -1 && i <= maxStep; };

  const add = () => {
    const variantName = (colorVariants && activeVariant != null) ? variantLabel(colorVariants[activeVariant]) : null;
    app.addToQuote({
      productId: product.id, name: product.name, detail: product.detail,
      kind: product.kind, qty, colors: isReady ? null : logo, piece: hasPiece ? piece : null,
      size: hasSize ? size : null, variant: variantName,
    });
    app.closeDetail();
    app.go('orcamento');   // mobile: aba orçamento
    app.openCart();        // desktop: abre o drawer do carrinho
  };
  const next = () => { if (isLast) add(); else { setStep(step + 1); setMaxStep(m => Math.max(m, step + 1)); } };

  const pieceObj = pieceOpts.find(c => c.id === piece);
  // a etapa "Cor da peça" e os thumbs de variação controlam o mesmo estado — escolher na etapa também troca a foto
  const selectPiece = (id) => {
    setPiece(id);
    if (colorVariants) {
      const vi = colorVariants.findIndex(c => c.id === id);
      if (vi >= 0) { setActiveVariant(vi); setMainImg(colorVariants[vi].img || product.img); }
    }
  };

  // fechar: Esc + confirmação leve se já houver etapas preenchidas (não descarta 4 passos num toque acidental)
  const tryClose = () => {
    if (!isReady && step > 0 && !window.confirm('Descartar as opções escolhidas para este produto?')) return;
    app.closeDetail();
  };
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') tryClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [step]);

  // ao avançar etapa, mantém o passo atual visível (sem rolar dentro do sheet à procura dele)
  const trailRef = React.useRef(null);
  const firstStepRun = React.useRef(true);
  React.useEffect(() => {
    if (firstStepRun.current) { firstStepRun.current = false; return; }
    try { trailRef.current && trailRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {}
  }, [step]);

  // gancho de conjunto: kit que contém este produto (complete o kit) ou 1–2 complementares de outra categoria
  const kitFor = React.useMemo(() => (product.kind === 'kit') ? null
    : PORCE_DATA.products.find(k => k.kind === 'kit' && k.id !== product.id && Array.isArray(k.bundle) && k.bundle.includes(product.id)),
    [product.id]);
  const complements = React.useMemo(() => {
    if (kitFor) return [];
    const pool = PORCE_DATA.products.filter(p2 => p2.id !== product.id && p2.cat !== product.cat);
    return [...pool.filter(p2 => p2.best), ...pool.filter(p2 => !p2.best)].slice(0, 2);
  }, [product.id, kitFor]);
  React.useEffect(() => {
    const list = kitFor ? [kitFor] : complements;
    if (!list.length) return;
    try { window.PORCE_TRACK && PORCE_TRACK('view_item_list', { item_list_name: kitFor ? 'complete-o-kit' : 'compre-em-conjunto', items: list.map(p2 => p2.id).join(',') }); } catch (e) {}
  }, [product.id]);
  const quickAdd = (p2, listName) => {
    try { window.PORCE_TRACK && PORCE_TRACK('select_item', { item_id: p2.id, item_list_name: listName }); } catch (e) {}
    const s2 = (p2.sizes && p2.sizes.length) ? (p2.sizes.includes(300) ? 300 : p2.sizes[0]) : null;
    app.addToQuote({ productId: p2.id, name: p2.name, detail: p2.detail, kind: p2.kind, qty: 1, colors: p2.ready ? null : 'colorido', piece: null, size: s2, variant: null });
    setAddedSug(m => ({ ...m, [p2.id]: true }));
  };

  // resumo cumulativo do rodapé — só o que já foi escolhido
  const summary = (isReady ? [`${qty} un`] : [
    hasSize && visited('size') ? `${size} ${product.unit || 'ml'}` : null,
    hasPiece && visited('piece') && pieceObj ? pieceObj.label : null,
    `${qty} un`,
    visited('logo') && logo ? (logo === 'colorido' ? 'multicor' : `logo ${logo} ${logo === '1' ? 'cor' : 'cores'}`) : null,
  ].filter(Boolean)).join(' · ');

  return (
    <>
      <div className="overlay" onClick={tryClose} />
      <div className="sheet pd-sheet" role="dialog" aria-modal="true" aria-label={displayName(product.name)}>
        <div className="sheet-grip" style={{ position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)', margin: 0, zIndex: 6, background: 'rgba(255,255,255,.8)', boxShadow: '0 1px 4px rgba(13,43,90,.3)' }} />
        <button onClick={tryClose} aria-label="Fechar" style={{ position: 'absolute', top: 14, right: 14, zIndex: 6, width: 40, height: 40, borderRadius: '50%', border: 'none', background: 'rgba(20,38,63,.5)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
          <PIcon name="close" size={22} stroke="#fff" />
        </button>
        <div className="scroll" style={{ flex: 1, minHeight: 0, height: 'auto', borderRadius: '26px 26px 0 0' }}>
          <div className="pd-cols">
          <div className="pd-media">
            <PPhoto kind={product.kind} illo={PORCE_ILLO.illoFor(product)} img={mainImg} color={hasPiece && product.cat === 'canecas' ? piece : null} slot={`pcat-${product.id}`} placeholder="Arraste a foto do produto" className="pd-photo" style={{ width: '100%' }}>
              {pieceObj && !pieceObj.glass && (
                <div style={{ position: 'absolute', bottom: 12, left: 12, display: 'flex', alignItems: 'center', gap: 7, background: 'rgba(255,255,255,.92)', padding: '5px 11px 5px 6px', borderRadius: 99, boxShadow: 'var(--sh-card)' }}>
                  <span style={{ width: 18, height: 18, borderRadius: '50%', background: pieceObj.hex, border: '1.5px solid rgba(0,0,0,.15)' }} />
                  <span style={{ fontSize: 12, fontWeight: 800, color: 'var(--navy)' }}>{pieceObj.label}</span>
                </div>
              )}
            </PPhoto>
          {colorVariants && (
            <div style={{ padding: '12px 16px 0' }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-soft)', marginBottom: 8, textTransform: 'uppercase', letterSpacing: '.5px' }}>Cor da peça</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {colorVariants.map((c, i) => (
                  <button key={i} onClick={() => { setActiveVariant(i); setMainImg(c.img || product.img); if (c.id && hasPiece) setPiece(c.id); }}
                    style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, border: 'none', background: 'none', cursor: 'pointer', padding: 2 }}>
                    <span style={{ width: 52, height: 52, borderRadius: 10, overflow: 'hidden', display: 'block', border: activeVariant === i ? '2.5px solid var(--gold)' : '1.5px solid var(--line)', boxShadow: activeVariant === i ? '0 0 0 2px var(--gold-soft)' : 'none', transition: 'all .15s' }}>
                      {c.img ? <img src={c.img} alt={variantLabel(c)} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>🎨</span>}
                    </span>
                    <span style={{ fontSize: 11.5, fontWeight: 700, color: activeVariant === i ? 'var(--gold-700)' : 'var(--ink-soft)', maxWidth: 58, textAlign: 'center', lineHeight: 1.2 }}>{variantLabel(c)}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
          {(gallery || product.video) && (
            <div style={{ display: 'flex', gap: 8, padding: '12px 16px 0', overflowX: 'auto' }}>
              {gallery && gallery.map((u, i) => (
                <button key={i} onClick={() => setMainImg(u)} style={{ width: 56, height: 56, borderRadius: 12, overflow: 'hidden', border: mainImg === u ? '2px solid var(--navy)' : '1.5px solid var(--line)', flex: 'none', padding: 0, cursor: 'pointer', background: '#fff' }}>
                  <img src={u} alt="" loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                </button>
              ))}
              {product.video && (
                <a href={product.video} target="_blank" rel="noopener noreferrer" title="Ver vídeo" style={{ width: 56, height: 56, borderRadius: 12, border: 'none', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--navy)', color: '#fff', textDecoration: 'none', fontSize: 20 }}>▶</a>
              )}
            </div>
          )}
          </div>

          <div className="pd-body">
          <div style={{ padding: '18px 20px 6px' }}>
            <div className="eyebrow">{PORCE_DATA.categories.find(c => c.id === product.cat)?.label}</div>
            <div className="h1" style={{ fontSize: 22, marginTop: 6, lineHeight: 1.32 }}>{product.name}</div>
            <div className="muted" style={{ fontSize: 13.5, marginTop: 12 }}>{hasSize ? `${size} ${product.unit || 'ml'}${product.detail ? ' · ' + product.detail : ''}` : product.detail}</div>
            <div className="quote-tag" style={{ fontSize: 14, marginTop: 8 }}>{priceTag(product)}</div>
            {isReady && product.stock != null && product.stock !== '' && (
              <div style={{ fontSize: 13, fontWeight: 800, marginTop: 8, color: Number(product.stock) > 0 ? 'var(--green)' : 'var(--danger)' }}>
                {Number(product.stock) > 0 ? `✓ ${product.stock} em estoque · pronta entrega` : 'Esgotado'}
              </div>
            )}
          </div>

          {/* trilha de etapas */}
          {!isReady && (
            <div ref={trailRef} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 20px 0' }}>
              {steps.map((s, i) => (
                <React.Fragment key={s}>
                  <button onClick={() => i < step && setStep(i)} aria-current={i === step ? 'step' : undefined}
                    style={{ display: 'flex', alignItems: 'center', gap: 7, border: 'none', background: 'none', padding: '10px 2px', cursor: i < step ? 'pointer' : 'default' }}>
                    <span style={{ width: 24, height: 24, borderRadius: '50%', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 800,
                      background: i < step ? 'var(--navy)' : i === step ? 'var(--gold)' : 'var(--porc-2)',
                      color: i < step ? '#fff' : i === step ? 'var(--navy-deep)' : 'var(--ink-soft)' }}>
                      {i < step ? '✓' : i + 1}
                    </span>
                    <span style={{ fontSize: 12, fontWeight: 800, color: i === step ? 'var(--navy)' : i < step ? 'var(--ink-soft)' : 'var(--ink-mute)', whiteSpace: 'nowrap' }}>{stepMeta[s]}</span>
                  </button>
                  {i < steps.length - 1 && <div style={{ flex: 1, height: 2, minWidth: 8, background: i < step ? 'var(--navy)' : 'var(--line)', borderRadius: 2 }} />}
                </React.Fragment>
              ))}
            </div>
          )}

          <div style={{ padding: '14px 20px 20px', minHeight: 150 }}>
            {/* ETAPA TAMANHO */}
            {cur === 'size' && (
              <div className="fade-in">
                <div className="eyebrow" style={{ marginBottom: 12 }}>Qual o tamanho?</div>
                <div style={{ display: 'flex', gap: 10 }}>
                  {sizeOpts.map(ml => (
                    <button key={ml} onClick={() => setSize(ml)} className="card"
                      style={{ flex: 1, padding: '16px 8px', border: size === ml ? '2px solid var(--gold)' : '2px solid transparent', cursor: 'pointer', textAlign: 'center', background: size === ml ? 'var(--gold-soft)' : 'var(--surface)' }}>
                      <div className="display" style={{ fontSize: 26, color: 'var(--navy)' }}>{ml}</div>
                      <div style={{ fontSize: 12, fontWeight: 800, color: size === ml ? 'var(--gold-700)' : 'var(--ink-soft)' }}>{product.unit || 'ml'}</div>
                    </button>
                  ))}
                </div>
                <div className="notice" style={{ marginTop: 16, background: 'var(--navy-soft)', color: 'var(--navy)' }}>
                  <PIcon name="cup" size={17} stroke="var(--navy)" />
                  <span>{displayName(product.name)} de <b>{size} {product.unit || 'ml'}</b>.</span>
                </div>
              </div>
            )}

            {/* ETAPA QUANTIDADE */}
            {cur === 'qty' && (
              <div className="fade-in">
                <div className="eyebrow" style={{ marginBottom: 12 }}>Quantas peças?</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12, flexWrap: 'wrap' }}>
                  <PStepper value={qty} min={minQty} onChange={(v) => setQty(Math.max(minQty, v))} />
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {(isReady ? [10, 20, 50, 100] : isSeri ? [35, 50, 100, 300] : [1, 10, 50, 100]).map(n => (
                      <button key={n} className={`chip ${qty === n ? 'active' : ''}`} style={{ padding: '9px 14px', fontSize: 12.5 }} onClick={() => setQty(n)}>{n}</button>
                    ))}
                  </div>
                </div>
                {isReady ? (
                  <div className="notice" style={{ background: 'var(--navy-soft)', color: 'var(--navy)' }}>
                    <PIcon name="truck" size={17} stroke="var(--navy)" />
                    <span><b>Pronta entrega</b> — estampas exclusivas Porceville, sem personalização.</span>
                  </div>
                ) : isSeri ? (
                  <div className="notice" style={{ background: 'rgba(46,125,91,.1)', color: 'var(--green)' }}>
                    <PIcon name="check" size={17} stroke="var(--green)" />
                    <span><b>Serigrafia</b> (logo {logo} {logo === '1' ? 'cor' : 'cores'}) — mínimo de {MIN} peças.</span>
                  </div>
                ) : (
                  <div className="notice" style={{ background: 'var(--navy-soft)', color: 'var(--navy)' }}>
                    <PIcon name="spark" size={17} stroke="var(--navy)" />
                    <span><b>Multicor</b> (sublimação) — a partir de 1 peça.</span>
                  </div>
                )}
                {!isReady && autoSwitched && qty < MIN && product.seri && (
                  <div className="notice" style={{ marginTop: 10 }}>
                    <PIcon name="palette" size={17} stroke="var(--gold-700)" />
                    <span>Abaixo de {MIN} peças a gravação muda automaticamente para <b>Multicor</b> (sublimação).</span>
                  </div>
                )}
              </div>
            )}

            {/* ETAPA COR DA LOGO */}
            {cur === 'logo' && (
              <div className="fade-in">
                <div className="eyebrow" style={{ marginBottom: 12 }}>Em quantas cores gravamos sua logo?</div>
                {product.seri && qty < MIN && (
                  <div className="notice" style={{ marginBottom: 12, background: 'var(--gold-soft)', color: 'var(--gold-700)', alignItems: 'center' }}>
                    <PIcon name="spark" size={17} stroke="var(--gold-700)" />
                    <span style={{ flex: 1 }}>Serigrafia (1–5 cores) a partir de <b>{MIN} peças</b>. Com <b>{qty} {qty === 1 ? 'peça' : 'peças'}</b>, a gravação é Multicor (sublimação).</span>
                    <button onClick={() => setQty(MIN)} className="chip" style={{ flex: 'none', background: 'var(--gold)', color: 'var(--navy-deep)', fontWeight: 800, padding: '7px 12px', fontSize: 12 }}>Usar {MIN}</button>
                  </div>
                )}
                <div style={{ display: 'flex', gap: 4 }}>
                  {logoOpts.map(o => {
                    const off = o.id !== 'colorido' && !seriEnabled;
                    return (
                      <button key={o.id} className={`color-opt ${logo === o.id ? 'sel' : ''}`} disabled={off}
                        title={off ? `A partir de ${MIN} peças` : undefined}
                        style={off ? { opacity: .35, cursor: 'default' } : undefined}
                        onClick={() => !off && setLogo(o.id)}>
                        <div className="dotwrap"><ColorDots opt={o} /></div>
                        <span className="lbl">{o.label}</span>
                      </button>
                    );
                  })}
                </div>
                <div style={{ marginTop: 14 }}>
                  {logo === 'colorido' ? (
                    <div className="notice" style={{ background: 'var(--navy-soft)', color: 'var(--navy)' }}>
                      <PIcon name="spark" size={17} stroke="var(--navy)" />
                      <span><b>Multicor</b> — sublimação, a partir de 1 peça.</span>
                    </div>
                  ) : logo ? (
                    <div className="notice" style={{ background: 'rgba(46,125,91,.1)', color: 'var(--green)' }}>
                      <PIcon name="check" size={17} stroke="var(--green)" />
                      <span><b>Serigrafia</b> — logo em {logo} {logo === '1' ? 'cor' : 'cores'}. Mínimo de {MIN} peças.</span>
                    </div>
                  ) : (
                    <div className="notice">
                      <PIcon name="palette" size={17} stroke="var(--gold-700)" />
                      <span>Multicor parte de 1 peça; 1–5 cores (serigrafia) a partir de {MIN}.</span>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* ETAPA COR DA PEÇA */}
            {cur === 'piece' && (
              <div className="fade-in">
                <div className="eyebrow" style={{ marginBottom: 12 }}>Qual a cor da {product.kind === 'glass' ? 'peça' : 'caneca'}?</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14 }}>
                  {pieceOpts.map(c => (
                    <button key={c.id} onClick={() => selectPiece(c.id)}
                      style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, border: 'none', background: 'none', cursor: 'pointer', width: 58, padding: '2px 0' }}>
                      <span style={{
                        width: 44, height: 44, borderRadius: '50%',
                        background: c.glass ? 'linear-gradient(135deg,#EAF2F7,#C3D6E4)' : c.hex,
                        border: piece === c.id ? '3px solid var(--gold)' : '2px solid var(--line)',
                        boxShadow: piece === c.id ? '0 0 0 3px var(--gold-soft)' : 'none',
                        transition: 'all .15s',
                      }} />
                      <span style={{ fontSize: 12, fontWeight: 700, color: piece === c.id ? 'var(--gold-700)' : 'var(--ink-soft)' }}>{c.label}</span>
                    </button>
                  ))}
                </div>
                <div className="notice" style={{ marginTop: 16, background: 'var(--navy-soft)', color: 'var(--navy)' }}>
                  <PIcon name="check" size={17} stroke="var(--navy)" />
                  <span>{displayName(product.name)} na cor <b>{pieceObj?.label}</b>{visited('qty') ? `, ${qty} un` : ''}{visited('logo') && logo ? `, logo ${logo === 'colorido' ? 'multicor' : logo + (logo === '1' ? ' cor' : ' cores')}` : ''}.</span>
                </div>
              </div>
            )}
            {/* ação da etapa logo abaixo do box de seleção */}
            <button className="btn btn-navy btn-block" style={{ marginTop: 18, padding: 15 }} onClick={next} disabled={!stepValid}>
              {isLast ? 'Adicionar ao orçamento' : 'Continuar'}
            </button>
          </div>
          {/* gancho de aumento de pedido: complete o kit / compre em conjunto */}
          {(kitFor || complements.length > 0) && (
            <div className="fade-in" style={{ padding: '0 20px 22px' }}>
              {kitFor ? (
                <div style={{ border: '1.5px solid var(--gold)', background: 'var(--gold-soft)', borderRadius: 'var(--r-md)', padding: 12, display: 'flex', gap: 12, alignItems: 'center' }}>
                  <PPhoto kind={kitFor.kind} illo={PORCE_ILLO.illoFor(kitFor)} img={kitFor.img} slot={`pcat-${kitFor.id}`} placeholder="" style={{ width: 58, height: 58, borderRadius: 12, flex: 'none' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <span className="chip-gold" style={{ fontSize: 10, padding: '3px 8px', borderRadius: 6 }}>★ Complete o kit</span>
                    <div style={{ fontWeight: 800, fontSize: 13.5, color: 'var(--navy)', marginTop: 5, lineHeight: 1.25 }}>{displayName(kitFor.name)}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>
                      {(kitFor.bundle || []).length > 1 ? `Este produto + ${kitFor.bundle.length - 1} ${kitFor.bundle.length === 2 ? 'item' : 'itens'} em um só conjunto.` : 'Conjunto pronto para presentear.'}
                    </div>
                  </div>
                  <button className="btn btn-gold btn-sm" style={{ flex: 'none' }} disabled={!!addedSug[kitFor.id]} onClick={() => quickAdd(kitFor, 'complete-o-kit')}>
                    {addedSug[kitFor.id] ? '✓ no orçamento' : 'Quero o kit'}
                  </button>
                </div>
              ) : (
                <div>
                  <div className="eyebrow" style={{ marginBottom: 10 }}>Compre em conjunto</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    {complements.map(c => (
                      <div key={c.id} style={{ display: 'flex', gap: 12, padding: 10, alignItems: 'center', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14 }}>
                        <PPhoto kind={c.kind} illo={PORCE_ILLO.illoFor(c)} img={c.img} slot={`pcat-${c.id}`} placeholder="" style={{ width: 48, height: 48, borderRadius: 10, flex: 'none' }} />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--navy)', lineHeight: 1.25, maxHeight: 33, overflow: 'hidden' }}>{displayName(c.name)}</div>
                          <div className="quote-tag" style={{ fontSize: 11, marginTop: 3 }}>{priceTag(c)}</div>
                        </div>
                        <button className="btn btn-ghost btn-sm" style={{ flex: 'none' }} disabled={!!addedSug[c.id]} onClick={() => quickAdd(c, 'compre-em-conjunto')}>
                          {addedSug[c.id] ? '✓ adicionado' : '+ adicionar'}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}
          </div>
          </div>
        </div>

        <div style={{ flex: 'none', background: 'var(--surface)', borderTop: '1px solid var(--line)', padding: '12px 18px 26px', display: 'flex', alignItems: 'center', gap: 12 }}>
          {step > 0 && (
            <button className="btn btn-ghost" style={{ flex: 'none', padding: '15px 16px' }} onClick={() => setStep(step - 1)} aria-label="voltar">
              <PIcon name="chevron" size={18} style={{ transform: 'rotate(180deg)' }} />
            </button>
          )}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: 'var(--ink-soft)', fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{summary}</div>
            <div className="quote-tag">{priceTag(product)}</div>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { PorceProductsScreen, PorceProductDetail });
