/* PORCEVILLE — Versão DESKTOP (catálogo web, sem cara de Instagram) */

function DeskFeatured({ p, app }) {
  if (!p) return null;
  return (
    <div className="pdesk-feat">
      <div className="feat-media">
        <PPhoto kind={p.kind} illo={PORCE_ILLO.illoFor(p)} img={p.img} slot={`pcat-${p.id}`} placeholder="Foto destaque" style={{ width: '100%', height: '100%', position: 'absolute', inset: 0 }} />
        <span className="chip-gold" style={{ position: 'absolute', top: 16, left: 16, fontSize: 11, padding: '5px 11px', borderRadius: 8 }}>★ Destaque da semana</span>
      </div>
      <div className="feat-body">
        <div className="eyebrow">{PORCE_DATA.categories.find(c => c.id === p.cat)?.label}</div>
        <h3 className="display" style={{ fontSize: 34, color: 'var(--navy)', margin: '10px 0 12px', lineHeight: 1.1 }}>{displayName(p.name)}</h3>
        <p className="muted" style={{ fontSize: 15, lineHeight: 1.55, marginBottom: 8, maxWidth: 420 }}>{p.desc}</p>
        <div className="muted" style={{ fontSize: 13, marginBottom: 20 }}>{(p.sizes && p.sizes.length) ? `${p.sizes.join(' / ')} ${p.unit || 'ml'}${p.detail ? ' · ' + p.detail : ''}` : (p.detail || '')}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <button className="btn btn-navy" onClick={() => app.openDetail(p.id)}>Personalizar agora</button>
          <span className="quote-tag" style={{ fontSize: 14 }}>{priceTag(p)}</span>
        </div>
      </div>
    </div>
  );
}

function DeskProductCard({ p, app }) {
  return (
    <div className="pdesk-pcard" onClick={() => app.openDetail(p.id)} style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div className="thumb">
        <PPhoto kind={p.kind} illo={PORCE_ILLO.illoFor(p)} img={p.img} slot={`pcat-${p.id}`} placeholder="Foto" style={{ width: '100%', aspectRatio: '1 / 1' }} />
        {p.best && <span className="chip-gold" style={{ position: 'absolute', top: 12, left: 12, fontSize: 11, padding: '4px 9px', borderRadius: 8 }}>★ Mais pedido</span>}
        {p.ready && <span className="chip-soft" style={{ position: 'absolute', top: 12, left: 12, fontSize: 11, padding: '4px 9px', borderRadius: 8 }}>Pronta entrega</span>}
      </div>
      <div style={{ padding: '16px 16px 16px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div className="display" style={{ fontSize: 18, color: 'var(--navy)', lineHeight: 1.2, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', minHeight: '2.4em' }}>{displayName(p.name)}</div>
        <div className="muted" style={{ fontSize: 12.5, marginTop: 5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{(p.sizes && p.sizes.length) ? `${p.sizes.join(' / ')} ${p.unit || 'ml'}${p.detail ? ' · ' + p.detail : ''}` : (p.detail || '\u00a0')}</div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto', paddingTop: 14 }}>
          <span className="quote-tag" style={{ fontSize: 13.5 }}>{priceTag(p)}</span>
          <span className="pdesk-addbtn"><PIcon name="plus" size={20} stroke="currentColor" /></span>
        </div>
      </div>
    </div>
  );
}

function DeskQuoteDrawer({ app, onClose }) {
  const pieces = app.quote.reduce((s, e) => s + e.qty, 0);
  return (
    <>
      <div className="overlay" style={{ position: 'fixed', zIndex: 125 }} onClick={onClose} />
      <aside className="pdesk-drawer">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '20px 22px 16px', borderBottom: '1px solid var(--line)' }}>
          <PIcon name="doc" size={20} stroke="var(--navy)" />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 16, color: 'var(--navy)', fontFamily: 'var(--font-display)' }}>Meu orçamento</div>
            <div className="muted" style={{ fontSize: 12 }}>{app.quote.length} {app.quote.length === 1 ? 'item' : 'itens'} · {pieces} peças · sem compromisso</div>
          </div>
          <button onClick={onClose} style={{ border: 'none', background: 'var(--porc-2)', borderRadius: '50%', width: 34, height: 34, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <PIcon name="close" size={18} stroke="var(--ink)" />
          </button>
        </div>

        <div className="scroll" style={{ flex: 1, padding: '16px 22px' }}>
          {app.quote.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '50px 10px', color: 'var(--ink-mute)' }}>
              <PIcon name="doc" size={34} stroke="var(--ink-mute)" />
              <p style={{ fontSize: 14, marginTop: 10 }}>Seu orçamento está vazio.<br />Adicione produtos do catálogo.</p>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {app.quote.map(e => (
                <div key={e.key} className="card" style={{ display: 'flex', gap: 12, padding: 12, alignItems: 'center' }}>
                  <PPhoto kind={e.kind} illo={PORCE_ILLO.illoFor(PORCE_DATA.getProduct(e.productId))} img={(PORCE_DATA.getProduct(e.productId)||{}).img} color={e.piece} slot={`pcat-${e.productId}`} placeholder="" style={{ width: 56, height: 56, borderRadius: 12, flex: 'none' }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--navy)' }}>{displayName(e.name)}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 2, lineHeight: 1.35 }}>{engravingLabel(e)}</div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                    <button onClick={() => app.removeFromQuote(e.key)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--ink-mute)' }}><PIcon name="trash" size={16} /></button>
                    <PStepper size="sm" value={e.qty} min={1} onChange={n => app.setQuoteQty(e.key, Math.max(1, n))} />
                  </div>
                </div>
              ))}
            </div>
          )}
          {app.quote.length > 0 && <PorceUpsellRow app={app} title="Adicione também" />}
        </div>

        {app.quote.length > 0 && (
          <div style={{ padding: '16px 22px 22px', borderTop: '1px solid var(--line)' }}>
            <div className="notice" style={{ marginBottom: 12 }}>
              <PIcon name="whats" size={16} stroke="var(--gold-700)" />
              <span>Enviamos os valores e prazos pelo WhatsApp em horário comercial.</span>
            </div>
            <button className="btn btn-whats btn-block" style={{ padding: 15 }}
              onClick={() => { onClose(); app.requestSend(); }}>
              <PIcon name="whats" size={19} stroke="#fff" /> Enviar orçamento
            </button>
          </div>
        )}
      </aside>
    </>
  );
}

function DeskBanner({ b }) {
  const [copied, setCopied] = React.useState(false);
  const act = () => {
    if (b.coupon) {
      try { navigator.clipboard && navigator.clipboard.writeText(b.coupon); } catch (e) {}
      setCopied(true); setTimeout(() => setCopied(false), 2000);
    } else if (b.onClick) b.onClick();
  };
  return (
    <button className={`pdesk-banner ${b.span}`} onClick={act}>
      <div className="bnr-bg">
        <PPhoto kind={b.kind} slot={b.slot} placeholder=" " style={{ width: '100%', height: '100%' }} />
        <div style={{ position: 'absolute', inset: 0, background: b.span === 'span4'
          ? 'linear-gradient(90deg, rgba(13,43,90,.92) 0%, rgba(13,43,90,.7) 45%, rgba(13,43,90,.15) 100%)'
          : 'linear-gradient(180deg, rgba(13,43,90,.4) 0%, rgba(13,43,90,.86) 100%)' }} />
      </div>
      <div className="bnr-content">
        <div style={{ fontSize: 11, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--gold)', fontWeight: 800 }}>{b.eyebrow}</div>
        <div className="display" style={{ fontSize: b.span === 'span4' ? 30 : 22, margin: '8px 0 6px', color: '#fff', lineHeight: 1.12 }}>{b.title}</div>
        <div style={{ fontSize: 13.5, color: 'rgba(255,255,255,.9)', lineHeight: 1.45, marginBottom: 14 }}>{b.sub}</div>
        {b.coupon ? (
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, pointerEvents: 'none' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, border: '1.5px dashed var(--gold)', borderRadius: 10, padding: '8px 14px', color: '#fff', fontWeight: 800, letterSpacing: '.08em', fontSize: 15 }}>
              {b.coupon}
            </span>
            <span className="btn btn-gold btn-sm">{copied ? '✓ Copiado!' : b.cta}</span>
          </span>
        ) : (
          <span className="btn btn-gold btn-sm" style={{ pointerEvents: 'none' }}>{b.cta}</span>
        )}
      </div>
    </button>
  );
}

function BannerCarousel() {
  // carrossel de banners full-width (base: banner do site original porceville.com.br).
  // lista editável via content.banners (array de URLs); fallback = banner original.
  const banners = (PORCE_DATA.content && Array.isArray(PORCE_DATA.content.banners) && PORCE_DATA.content.banners.length)
    ? PORCE_DATA.content.banners : ['uploads/banner/original-1920x520.png'];
  const [i, setI] = React.useState(0);
  React.useEffect(() => {
    if (banners.length < 2) return;
    const t = setInterval(() => setI(v => (v + 1) % banners.length), 5000);
    return () => clearInterval(t);
  }, [banners.length]);
  const waBanner = `https://wa.me/${PORCE_DATA.WHATS}?text=${encodeURIComponent('Olá! Vim pelo site da Porceville e preciso de brindes personalizados. Pode me ajudar com um orçamento?')}`;
  return (
    <div style={{ position: 'relative', width: '100%', overflow: 'hidden' }}>
      <a href={waBanner} onClick={() => PORCE_PING('banner', '🟢 Visitante clicou no banner Fale com o Consultor — deve te chamar em instantes')} target="_blank" rel="noopener noreferrer" aria-label="Falar com nosso consultor no WhatsApp" style={{ display: 'block', lineHeight: 0, cursor: 'pointer' }}>
        <img src={banners[i]} alt="Porceville — brindes personalizados" style={{ width: '100%', display: 'block' }} />
      </a>
      {banners.length > 1 && (
        <div style={{ position: 'absolute', bottom: 14, left: 0, right: 0, display: 'flex', gap: 8, justifyContent: 'center' }}>
          {banners.map((_, d) => (
            <button key={d} type="button" onClick={() => setI(d)} aria-label={`banner ${d + 1}`}
              style={{ width: 10, height: 10, borderRadius: '50%', border: 'none', cursor: 'pointer', background: d === i ? 'var(--navy)' : 'rgba(13,43,90,.28)' }} />
          ))}
        </div>
      )}
    </div>
  );
}

/* Captura de lead da home: "deixe seu contato e o que precisa — entramos em contato" */
function HomeLeadForm({ dark }) {
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [need, setNeed] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const valid = name.trim().length >= 2 && phone.replace(/\D/g, '').length >= 10;
  const [fallback, setFallback] = React.useState(false);
  const submit = async () => {
    if (!valid || busy) return;
    setBusy(true);
    const summary = (need || '').trim() || 'Contato pela home';
    const r = await porceCaptureLead({ customer_name: name.trim(), customer_phone: phone.trim(),
      source: 'lead-home', pieces: 0, summary });
    setBusy(false); setFallback(!r.saved); setDone(true);
  };
  const waMsg = `https://wa.me/${PORCE_DATA.WHATS}?text=${encodeURIComponent(`Olá, Porceville! Sou ${name.trim()}. ${(need || '').trim() || 'Gostaria de um orçamento.'}`)}`;
  if (done) {
    return (
      <div style={{ textAlign: 'center', padding: '30px 10px' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--green)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
          <PIcon name="check" size={28} stroke="#fff" sw={2.4} />
        </div>
        <div className="display" style={{ fontSize: 24, color: dark ? '#fff' : 'var(--navy)' }}>{fallback ? 'Quase lá!' : `Recebido, ${name.trim().split(' ')[0]}!`}</div>
        <p style={{ fontSize: 14, marginTop: 8, color: dark ? 'rgba(255,255,255,.8)' : 'var(--ink-mute)' }}>{fallback ? 'Não conseguimos registrar agora — fale direto com a gente no WhatsApp:' : 'Nossa equipe entra em contato em horário comercial.'}</p>
        {fallback && <a className="btn btn-whats" href={waMsg} target="_blank" rel="noopener noreferrer" style={{ marginTop: 14, padding: '13px 26px', display: 'inline-flex' }}>Abrir WhatsApp</a>}
      </div>
    );
  }
  const inputSt = { padding: '13px 14px', border: '1.5px solid ' + (dark ? 'rgba(255,255,255,.25)' : 'var(--line)'), borderRadius: 12, fontSize: 15, background: '#fff' };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="display" style={{ fontSize: 30, color: dark ? '#fff' : 'var(--navy)', lineHeight: 1.15 }}>{PORCE_TX('lead_titulo', 'Não achou o que precisa?')}</div>
      <p style={{ fontSize: 14.5, lineHeight: 1.55, margin: 0, color: dark ? 'rgba(255,255,255,.85)' : 'var(--ink-mute)' }}>{PORCE_TX('lead_sub', 'Deixe seu contato e o que você procura — nossa equipe monta o orçamento e retorna. Sem compromisso.')}</p>
      <input className="in" placeholder="Seu nome *" value={name} onChange={e => setName(e.target.value)} style={inputSt} />
      <input className="in" placeholder="WhatsApp / telefone *" value={phone} onChange={e => setPhone(e.target.value)} inputMode="tel" style={inputSt} />
      <textarea className="in" rows={3} placeholder="O que você precisa? (produto, quantidade, evento...)" value={need} onChange={e => setNeed(e.target.value)}
        style={{ ...inputSt, resize: 'vertical', fontFamily: 'inherit' }} />
      <button type="button" className={dark ? 'btn btn-gold btn-block' : 'btn btn-navy btn-block'} disabled={!valid || busy} onClick={submit}
        style={{ padding: 15, fontSize: 15.5, fontWeight: 800, opacity: valid && !busy ? 1 : .55 }}>
        {busy ? 'Enviando…' : 'Quero um orçamento'}
      </button>
    </div>
  );
}

/* Home curta e orgânica: carrossel + prévia de categorias misturada com banners + captura de lead */
function DesktopHome({ app, onEnter, onOpenCat }) {
  const temFotoReal = p => p.img && !String(p.img).includes('falta-foto');
  const secao = id => PORCE_DATA.products
    .filter(p => p.cat === id)
    .sort((a, b) => (temFotoReal(b) - temFotoReal(a)) || (!!b.best - !!a.best) || 0)
    .slice(0, 5);
  const blocos = PORCE_DATA.categories
    .filter(c => c.id !== 'todos')
    .map(c => ({ cat: c, items: secao(c.id) }))
    .filter(b => b.items.length >= 3)
    .slice(0, 3);
  const capa = (PORCE_DATA.content && PORCE_DATA.content.landing && PORCE_DATA.content.landing.capa_story) || 'uploads/banner/capa-story.jpg';
  // fileira de categorias estilo editorial: foto do produto + pílula com o nome (ref. Khoomi/Behance)
  const catCards = PORCE_DATA.categories
    .map(c => {
      const p = PORCE_DATA.products.find(x => x.cat === c.id && temFotoReal(x));
      return p ? { cat: c, img: p.img } : null;
    })
    .filter(Boolean).slice(0, 5);
  const Secao = ({ b }) => (
    <>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', margin: '44px 0 18px' }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--gold-700)', fontWeight: 800, marginBottom: 6 }}>● Linha {b.cat.label}</div>
          <h2 className="display" style={{ fontSize: 34, color: 'var(--navy)', margin: 0, lineHeight: 1.05 }}>{b.cat.label} personalizad{/[ao]s?$/i.test((b.cat.label || '').trim().split(' ')[0]) && !/os$/i.test((b.cat.label || '').trim().split(' ')[0]) ? 'as' : 'os'}</h2>
        </div>
        <button type="button" onClick={() => onOpenCat(b.cat.id)}
          style={{ border: '1.5px solid var(--navy)', background: 'none', cursor: 'pointer', color: 'var(--navy)', fontWeight: 800, fontSize: 12.5, letterSpacing: '.12em', textTransform: 'uppercase', padding: '12px 24px', borderRadius: 99 }}>Ver todos</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(212px, 1fr))', gap: 16 }}>
        {b.items.map(p => <DeskProductCard key={p.id} p={p} app={app} />)}
      </div>
    </>
  );
  return (
    <div style={{ background: 'var(--porc-bg)', position: 'relative', overflow: 'hidden' }}>
      <BannerCarousel />
      {/* halos decorativos soltos — quebram a sensação de blocos */}
      <div style={{ position: 'absolute', top: 480, right: '-9%', width: 400, height: 400, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,210,0,.10), transparent 66%)', pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', top: 1500, left: '-7%', width: 380, height: 380, borderRadius: '50%', background: 'radial-gradient(circle, rgba(13,43,90,.08), transparent 70%)', pointerEvents: 'none' }} />

      <div style={{ width: '88%', maxWidth: 1240, margin: '0 auto', padding: '10px 0 0', position: 'relative' }}>
        {/* compre por categoria — cards foto + pílula (ref. Khoomi) */}
        {catCards.length > 1 && (
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(catCards.length, 5)}, 1fr)`, gap: 16, marginTop: 26 }}>
            {catCards.map(({ cat: c, img }) => (
              <button key={c.id} type="button" onClick={() => onOpenCat(c.id)}
                style={{ position: 'relative', border: 'none', padding: 0, cursor: 'pointer', borderRadius: 16, overflow: 'hidden', aspectRatio: '1 / 1.08', background: '#fff', boxShadow: '0 10px 26px rgba(13,43,90,.10)' }}>
                <img src={img} alt={c.label} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
                <span style={{ position: 'absolute', left: '50%', bottom: 14, transform: 'translateX(-50%)', background: 'rgba(255,255,255,.94)', color: 'var(--navy)', fontWeight: 800, fontSize: 12, letterSpacing: '.14em', textTransform: 'uppercase', padding: '9px 18px', borderRadius: 99, whiteSpace: 'nowrap', boxShadow: '0 6px 16px rgba(0,0,0,.12)' }}>{c.label}</span>
              </button>
            ))}
          </div>
        )}
        {blocos[0] && <Secao b={blocos[0]} />}

        {/* barra única completa — imagem editável no admin (Conteúdo & Banner) */}
        <button type="button" onClick={() => onOpenCat('todos')} aria-label="Ver catálogo"
          style={{ display: 'block', width: '100%', border: 'none', padding: 0, background: 'none', cursor: 'pointer', margin: '40px 0 8px', borderRadius: 20, overflow: 'hidden', boxShadow: '0 18px 44px rgba(13,43,90,.22)', lineHeight: 0 }}>
          <img src={((PORCE_DATA.content && PORCE_DATA.content.banner_corp) || {}).image || 'uploads/banner/banner-corporativo.jpg'} alt="Brindes corporativos — sua marca em cada detalhe" style={{ width: '100%', height: 200, objectFit: 'cover', display: 'block' }} />
        </button>

        {blocos[1] && <Secao b={blocos[1]} />}
      </div>

      {/* faixa navy diagonal full-bleed: capa do celular invade a faixa + lead direto sobre ela */}
      <div style={{ position: 'relative', marginTop: 100, marginBottom: 10, background: 'linear-gradient(160deg, #16335F 0%, #0D2B5A 55%, #101F3C 100%)', clipPath: 'polygon(0 46px, 100% 0, 100% 100%, 0 100%)', paddingTop: 46 }}>
        <div style={{ position: 'absolute', top: '10%', right: '-4%', width: 380, height: 380, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,210,0,.22), transparent 70%)', pointerEvents: 'none' }} />
        <div style={{ width: '88%', maxWidth: 1240, margin: '0 auto', display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 44, alignItems: 'center', padding: '30px 0 64px' }}>
          <button type="button" onClick={onEnter} aria-label="Ver catálogo"
            style={{ border: 'none', padding: 0, background: 'none', cursor: 'pointer', lineHeight: 0, transform: 'rotate(-3deg) translateY(-70px)', maxWidth: 430, width: '100%', justifySelf: 'center' }}>
            <img src={capa} alt="Porceville" style={{ width: '100%', height: 560, objectFit: 'cover', objectPosition: 'top', display: 'block', borderRadius: 22, border: '5px solid rgba(255,255,255,.9)', boxShadow: '0 44px 100px rgba(0,0,0,.5)' }} />
          </button>
          <div style={{ maxWidth: 520 }}><HomeLeadForm dark /></div>
        </div>
      </div>

      <div style={{ width: '88%', maxWidth: 1240, margin: '0 auto', position: 'relative' }}>
        {blocos[2] && <Secao b={blocos[2]} />}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '36px 24px 52px' }}>
        <button type="button" className="btn btn-navy" style={{ padding: '17px 64px', fontSize: 16, boxShadow: '0 16px 36px rgba(13,43,90,.4)' }} onClick={onEnter}>
          Ver catálogo completo
        </button>
      </div>
    </div>
  );
}

function DeskSearch({ app }) {
  const [q, setQ] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const norm = t => String(t || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  const res = q.trim().length >= 2
    ? PORCE_DATA.products.filter(p => norm(p.name + ' ' + (p.detail || '')).includes(norm(q))).slice(0, 8)
    : [];
  return (
    <div style={{ position: 'relative', flex: '0 1 340px' }}>
      <input value={q} placeholder="Buscar produto…" aria-label="Buscar produto"
        onChange={e => { setQ(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 180)}
        style={{ width: '100%', padding: '10px 16px', borderRadius: 99, border: '1.5px solid var(--line)', fontSize: 14, background: '#fff', outline: 'none' }} />
      {open && res.length > 0 && (
        <div style={{ position: 'absolute', top: '110%', left: 0, right: 0, background: '#fff', borderRadius: 14, boxShadow: '0 20px 50px rgba(13,43,90,.22)', border: '1px solid var(--line)', overflow: 'hidden', zIndex: 200 }}>
          {res.map(p => (
            <button key={p.id} type="button" onMouseDown={() => { app.openDetail(p.id); setQ(''); setOpen(false); }}
              style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '9px 12px', border: 'none', background: 'none', cursor: 'pointer', textAlign: 'left' }}>
              <img src={p.img} alt="" style={{ width: 38, height: 38, borderRadius: 8, objectFit: 'cover', flex: 'none', background: '#f3f3f3' }} />
              <span style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--navy)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName(p.name)}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function PorceDesktop({ app }) {
  const [landed, setLanded] = React.useState(false);
  const [cat, setCat] = React.useState('todos');
  const [sub, setSub] = React.useState(null);   // sub-categoria expandida no accordion
  const gridRef = React.useRef(null);
  // menu superior por TIPO DE MATERIAL (porcelana/vidro) + pronta entrega + kits;
  // ids de categoria antigos (cards da home: canecas/copos/chopp/mesa) seguem como fallback.
  const MATERIAIS = [
    { id: 'todos', label: 'Todos', test: () => true },
    { id: 'porcelana', label: 'Porcelana', test: p => p.kind === 'porcelain' || p.kind === 'sublime' },
    { id: 'vidro', label: 'Vidro', test: p => p.kind === 'glass' || p.kind === 'chopp' },
    { id: 'pronta', label: 'Pronta Entrega', test: p => !!p.ready },
  ];
  const mat = MATERIAIS.find(m => m.id === cat);
  const list = mat ? PORCE_DATA.products.filter(mat.test) : PORCE_DATA.products.filter(p => p.cat === cat);
  const tituloCat = mat ? (mat.id === 'todos' ? 'Catálogo' : mat.label)
    : ((PORCE_DATA.categories.find(c => c.id === cat) || {}).label || 'Catálogo');
  React.useEffect(() => { setSub(null); }, [cat]);

  return (
    <div className="pdesk">
      <FloatBar />
      <header className="pdesk-head2">
        <div className="pdesk-head2-inner">
          <button onClick={() => { setCat('todos'); setLanded(false); }} title="Início" style={{ border: 'none', background: 'none', cursor: 'pointer', flex: 'none' }}>
            <PorceWordmark size={24} />
          </button>
          <nav className="pdesk-topnav">
            {MATERIAIS.filter(m => m.id !== 'todos').map(m => (
              <button key={m.id} className={`pdesk-navlink ${cat === m.id ? 'active' : ''}`} onClick={() => { setCat(m.id); setLanded(true); }}>{m.label}</button>
            ))}
          </nav>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flex: 'none' }}>
            <DeskSearch app={app} />
            <button onClick={() => app.openCart()} className="btn btn-navy btn-sm" style={{ position: 'relative', gap: 8 }}>
              <PIcon name="doc" size={17} stroke="#fff" /> Meu orçamento
              {app.quoteCount > 0 && <span style={{ background: 'var(--gold)', color: 'var(--navy-deep)', borderRadius: 99, fontSize: 11, fontWeight: 800, padding: '1px 7px' }}>{app.quoteCount}</span>}
            </button>
          </div>
        </div>
      </header>

      {/* home curta (prévia + banners + lead) até navegar; catálogo completo depois */}
      {!landed && <DesktopHome app={app} onEnter={() => setLanded(true)} onOpenCat={c => { setCat(c); setLanded(true); }} />}

      {landed && (
      <main className="pdesk-main" ref={gridRef}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 24 }}>
          <h2 className="display" style={{ fontSize: 28, color: 'var(--navy)' }}>{tituloCat}</h2>
          <span className="muted" style={{ fontSize: 13 }}>{list.length} produtos · sob orçamento</span>
        </div>

        {(() => {
          const featProduct = list.find(p => p.best) || list[0];
          // sub-categorias dinâmicas pelo tipo no nome (Taças, Copos, Canecos...) — accordion expansível
          // sub-categoria: p.sub (definida no admin, bate com categories.subs) vence sempre;
          // heurística por nome só cobre produto sem sub setado. null = sem sub identificável,
          // vai pra "Outros" — não existe mais lista fixa de nomes "válidos" pra bater contra
          // (havia um bug real aqui: sub-categorias de verdade como "Espumante"/"Vinho/Água"/
          // "Aperitivo/Dose" nunca batiam numa lista pensada pra nomes de CATEGORIA, então todo
          // produto com sub configurada no admin caía em "Outros" mesmo estando correto).
          const subTipo = p => {
            if (p.sub) return p.sub;
            const n = (p.name || '').replace(/^\*/, '').trim().toLowerCase();
            if (/^ta[çc]a/.test(n)) return 'Taças';
            if (/^caneco|caneca de chopp/.test(n)) return 'Canecos de Chopp';
            if (/^caneca/.test(n)) return 'Canecas';
            if (/^copo/.test(n)) return 'Copos';
            if (/^x[íi]cara/.test(n)) return 'Xícaras';
            if (/^prato/.test(n)) return 'Pratos';
            if (/^tigela|^bowl/.test(n)) return 'Tigelas';
            if (/^bandeja/.test(n)) return 'Bandejas';
            if (/^kit/.test(n) || p.kind === 'kit') return 'Kits';
            return null;
          };
          const grupos = {};
          list.filter(p => p !== featProduct).forEach(p => { const g = subTipo(p) || 'Outros'; (grupos[g] = grupos[g] || []).push(p); });
          // prateleira com mais produtos primeiro (mais relevante); "Outros" sempre por último
          const nomes = Object.keys(grupos).filter(g => g !== 'Outros').sort((a, b) => grupos[b].length - grupos[a].length);
          if (grupos['Outros'] && grupos['Outros'].length) nomes.push('Outros');
          return (
            <>
              {featProduct && <div className="pdesk-grid" style={{ marginBottom: 26 }}><DeskFeatured p={featProduct} app={app} /></div>}
              {nomes.length <= 1 ? (
                <div className="pdesk-grid">{list.filter(p => p !== featProduct).map(p => <DeskProductCard key={p.id} p={p} app={app} />)}</div>
              ) : nomes.map(g => {
                const aberto = sub === g;
                const mostrar = aberto ? grupos[g] : grupos[g].slice(0, 3);
                return (
                  /* shelf da linha: banner vertical fixo + fileira que EXPANDE NA HORIZONTAL (scroll lateral) */
                  <div key={g} style={{ display: 'grid', gridTemplateColumns: 'minmax(175px, 205px) 1fr', gap: 16, alignItems: 'stretch', marginBottom: 18 }}>
                    <button type="button" onClick={() => setSub(aberto ? null : g)}
                      style={{ border: 'none', cursor: 'pointer', borderRadius: 18, padding: '26px 20px', textAlign: 'left', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', gap: 14, background: 'linear-gradient(165deg, #16335F 0%, #0D2B5A 60%, #101F3C 100%)', boxShadow: '0 16px 36px rgba(13,43,90,.22)', ...(aberto ? { alignSelf: 'start', position: 'sticky', top: 86, minHeight: 220 } : {}) }}>
                      <div>
                        <div style={{ fontSize: 10.5, letterSpacing: '.16em', textTransform: 'uppercase', color: 'var(--gold)', fontWeight: 800 }}>Linha</div>
                        <div className="display" style={{ fontSize: 25, color: '#fff', lineHeight: 1.1, marginTop: 8 }}>{g}</div>
                      </div>
                      <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.78)', fontWeight: 700 }}>
                        {grupos[g].length} {grupos[g].length === 1 ? 'produto' : 'produtos'}
                        <span style={{ display: 'block', marginTop: 6, color: 'var(--gold)' }}>{aberto ? '‹ Recolher' : 'Ver todos ›'}</span>
                      </div>
                    </button>
                    <div style={{ display: 'flex', gap: 16, flexWrap: aberto ? 'wrap' : 'nowrap', overflow: 'hidden' }}>
                      {mostrar.map(p => (
                        <div key={p.id} style={{ flex: aberto ? '0 0 250px' : '1 1 220px', maxWidth: aberto ? 250 : 280, minWidth: 200 }}><DeskProductCard p={p} app={app} /></div>
                      ))}
                      {!aberto && grupos[g].length > 3 && (
                        <button type="button" onClick={() => setSub(g)}
                          style={{ flex: '0 0 132px', border: '1.5px dashed var(--gold)', background: 'var(--gold-soft)', borderRadius: 18, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--navy)', fontWeight: 800, fontSize: 14.5 }}>
                          <span style={{ fontSize: 24, color: 'var(--gold-700)' }}>›</span>
                          Ver todos
                          <span className="muted" style={{ fontSize: 11.5, fontWeight: 600 }}>+{grupos[g].length - 3}</span>
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </>
          );
        })()}

        <div style={{ textAlign: 'center', marginTop: 64, paddingTop: 30, borderTop: '1px solid var(--line)' }}>
          <PorceWordmark size={18} />
          <div className="muted" style={{ fontSize: 12.5, marginTop: 6, lineHeight: 1.6 }}>
            {PORCE_TX('rodape_tagline', 'Transformando ideias em peças que permanecem.')}<br />{PORCE_TX('rodape_info', 'Joinville · SC · (47) 3025-4400')}
          </div>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 14 }}>
            <a href={`https://wa.me/${PORCE_DATA.WHATS}?text=${encodeURIComponent('Olá, Porceville! Tenho uma dúvida.')}`} target="_blank" rel="noopener noreferrer"
              className="btn btn-ghost btn-sm" style={{ gap: 8, textDecoration: 'none', color: 'var(--green)' }}>
              <PIcon name="whats" size={16} stroke="var(--green)" /> Dúvidas no WhatsApp
            </a>
            <button onClick={app.openAdmin} className="btn btn-ghost btn-sm" style={{ gap: 8, color: 'var(--ink-mute)' }}>
              <PIcon name="lock" size={14} stroke="var(--ink-mute)" /> Área comercial
            </button>
          </div>
        </div>
      </main>
      )}

      <WhatsFab bottom={24} />
      {!landed && <CupomPopup />}
      {app.cartOpen && <DeskQuoteDrawer app={app} onClose={() => app.closeCart()} />}
      {app.detailId && <div className="pdesk-modal-host"><PorceProductDetail app={app} /></div>}
      {app.admin && <div className="pdesk-modal-host"><AdminPanel app={app} /></div>}
      {app.capturing && <div className="pdesk-modal-host"><OrderCaptureModal app={app} /></div>}
    </div>
  );
}

Object.assign(window, { PorceDesktop, HomeLeadForm, BannerCarousel });
