/* PORCEVILLE — Orçamento (lista + envio WhatsApp) e histórico */

function buildWhatsMessage(quote) {
  const lines = quote.map(e => {
    const grav = e.colors === 'colorido' ? 'multicor (sublimação)'
      : e.colors ? `logo em ${e.colors} ${e.colors === '1' ? 'cor' : 'cores'} (serigrafia)`
      : 'pronta entrega';
    const pc = e.piece ? (PORCE_DATA.pieceColors.find(c => c.id === e.piece)?.label) : null;
    const ml = e.size ? `${e.size}ml ` : '';
    return `• ${e.qty}× ${ml}${e.name} — ${grav}${pc ? `, peça ${pc.toLowerCase()}` : ''}`;
  });
  return encodeURIComponent(
    `Olá, Porceville! Gostaria de um orçamento:\n\n${lines.join('\n')}\n\nAguardo o retorno. Obrigado!`
  );
}

function porceUpsell(app, max) {
  const inCart = new Set(app.quote.map(e => e.productId));
  const pool = PORCE_DATA.products.filter(p => !inCart.has(p.id));
  // categoria dominante do carrinho → prioriza complementares (cat diferente)
  const catCount = {};
  app.quote.forEach(e => { const p = PORCE_DATA.getProduct(e.productId); if (p) catCount[p.cat] = (catCount[p.cat] || 0) + 1; });
  const domCat = Object.keys(catCount).sort((a, b) => catCount[b] - catCount[a])[0] || null;
  // kits cujo bundle contém itens já no carrinho vão pro topo, com selo "complete o kit"
  const kits = pool.filter(p => p.kind === 'kit' && Array.isArray(p.bundle) && p.bundle.some(id => inCart.has(id)));
  const rest = pool.filter(p => kits.indexOf(p) === -1);
  const comp = rest.filter(p => domCat && p.cat !== domCat);
  const same = rest.filter(p => comp.indexOf(p) === -1);
  const rank = arr => [...arr.filter(p => p.best), ...arr.filter(p => !p.best)];
  return [...kits.map(p => ({ ...p, _kitMatch: true })), ...rank(comp), ...rank(same)].slice(0, max || 6);
}

function PorceUpsellRow({ app, title }) {
  // lista congelada no mount: adicionar um item não embaralha a fileira nem some com o card
  const sug = React.useMemo(() => porceUpsell(app, 8), []);
  const [added, setAdded] = React.useState({});
  React.useEffect(() => {
    if (!sug.length) return;
    try { window.PORCE_TRACK && PORCE_TRACK('view_item_list', { item_list_name: 'adicione-tambem', items: sug.map(p => p.id).join(',') }); } catch (e) {}
  }, []);
  if (!sug.length) return null;
  // adição direta com defaults seguros — sem passar pelo detalhe de 4 passos
  const quickAdd = (p) => {
    try { window.PORCE_TRACK && PORCE_TRACK('select_item', { item_id: p.id, item_list_name: p._kitMatch ? 'complete-o-kit' : 'adicione-tambem' }); } catch (e) {}
    const size = (p.sizes && p.sizes.length) ? (p.sizes.includes(300) ? 300 : p.sizes[0]) : null;
    app.addToQuote({ productId: p.id, name: p.name, detail: p.detail, kind: p.kind, qty: 1, colors: p.ready ? null : 'colorido', piece: null, size, variant: null });
    setAdded(m => ({ ...m, [p.id]: true }));
  };
  return (
    <div style={{ padding: '18px 18px 4px' }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>{title || 'Adicione também'}</div>
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4 }}>
        {sug.map(p => (
          <div key={p.id} style={{ flex: 'none', width: 128, border: p._kitMatch ? '1.5px solid var(--gold)' : '1px solid var(--line)', background: 'var(--surface)', borderRadius: 14, overflow: 'hidden', textAlign: 'left' }}>
            <div onClick={() => app.openDetail(p.id)} style={{ position: 'relative', cursor: 'pointer' }}>
              <PPhoto kind={p.kind} illo={PORCE_ILLO.illoFor(p)} img={p.img} slot={`pcat-${p.id}`} placeholder="" style={{ width: '100%', aspectRatio: '1 / 1' }} />
              {p._kitMatch && <span className="chip-gold" style={{ position: 'absolute', top: 6, left: 6, fontSize: 9.5, padding: '3px 7px', borderRadius: 6 }}>Complete o kit</span>}
            </div>
            <div style={{ padding: '7px 9px 9px' }}>
              <div style={{ fontWeight: 700, fontSize: 11.5, color: 'var(--navy)', lineHeight: 1.2, height: 28, overflow: 'hidden' }}>{displayName(p.name)}</div>
              <div className="quote-tag" style={{ fontSize: 10.5, marginTop: 3 }}>{priceTag(p)}</div>
              <button onClick={() => quickAdd(p)} disabled={!!added[p.id]}
                style={{ marginTop: 7, width: '100%', border: 'none', borderRadius: 8, padding: '8px 6px', fontSize: 11.5, fontWeight: 800,
                  cursor: added[p.id] ? 'default' : 'pointer', fontFamily: 'var(--font-body)',
                  background: added[p.id] ? 'rgba(46,125,91,.12)' : 'var(--navy)', color: added[p.id] ? 'var(--green)' : '#fff' }}>
                {added[p.id] ? '✓ adicionado' : '+ adicionar'}
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PorceQuoteScreen({ app }) {
  const total = app.quote.reduce((s, e) => s + e.qty, 0);

  if (app.quote.length === 0) {
    return (
      <div className="scroll" style={{ paddingBottom: 28 }}>
        <PorceHeader title="Orçamento" />
        <div style={{ textAlign: 'center', padding: '52px 30px' }}>
          <div style={{ width: 74, height: 74, borderRadius: '50%', background: 'var(--porc-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <PIcon name="doc" size={32} stroke="var(--ink-mute)" />
          </div>
          <div className="h2">Seu orçamento está vazio</div>
          <p className="muted" style={{ fontSize: 14, margin: '8px auto 22px', maxWidth: 250, lineHeight: 1.5 }}>
            Adicione produtos com a quantidade e as cores da sua logo — a gente responde com os valores.
          </p>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
            <button className="btn btn-ghost" onClick={() => app.go('produtos')}>Ver produtos</button>
            <button className="btn btn-navy" onClick={() => app.go('caco')}>Falar com o Caco</button>
          </div>
        </div>
        <PorceFooter app={app} />
      </div>
    );
  }

  return (
    <div className="scroll" style={{ paddingBottom: 130 }}>
      <PorceHeader title="Orçamento" />
      <div style={{ padding: '0 18px 6px', display: 'flex', alignItems: 'center', gap: 8 }}>
        <span className="chip-soft" style={{ padding: '5px 11px', borderRadius: 8, fontSize: 12 }}>{app.quote.length} {app.quote.length === 1 ? 'item' : 'itens'} · {total} peças</span>
        <span className="muted" style={{ fontSize: 12.5 }}>Sem compromisso</span>
      </div>

      <div style={{ padding: '8px 18px 0', 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: 62, height: 62, borderRadius: 14, flex: 'none' }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 800, fontSize: 14.5, color: 'var(--navy)' }}>{displayName(e.name)}</div>
              <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{engravingLabel(e)}</div>
              <div className="quote-tag" style={{ marginTop: 4 }}>Sob orçamento</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8 }}>
              <button onClick={() => app.removeFromQuote(e.key)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--ink-mute)' }}><PIcon name="trash" size={18} /></button>
              <PStepper size="sm" value={e.qty} min={1} onChange={n => app.setQuoteQty(e.key, Math.max(1, n))} />
            </div>
          </div>
        ))}
      </div>

      <PorceUpsellRow app={app} title="Adicione também ao orçamento" />

      <div className="notice" style={{ margin: '16px 18px 0' }}>
        <PIcon name="whats" size={17} stroke="var(--gold-700)" />
        <span>Enviando pelo WhatsApp, nossa equipe responde com valores e prazos em horário comercial.</span>
      </div>

      <PorceFooter app={app} />

      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 18px 14px', background: 'linear-gradient(180deg, transparent, var(--porc-bg) 30%)' }}>
        <button className="btn btn-whats btn-block" style={{ padding: '16px', fontSize: 16 }}
          onClick={() => app.requestSend()}>
          <PIcon name="whats" size={20} stroke="#fff" /> Enviar orçamento pelo WhatsApp
        </button>
      </div>
    </div>
  );
}

function PorceHeader({ title }) {
  return (
    <div style={{ paddingTop: 58, paddingBottom: 8, position: 'sticky', top: 0, background: 'var(--porc-bg)', zIndex: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 18px' }}>
        <div className="h1">{title}</div>
        <PorceWordmark size={13} />
      </div>
    </div>
  );
}

function PorceFooter({ app }) {
  return (
    <div style={{ textAlign: 'center', padding: '28px 24px 10px' }}>
      <div className="wordmark" style={{ fontSize: 16 }}>Porce<span className="ville">ville</span></div>
      <div className="muted" style={{ fontSize: 12, marginTop: 4, lineHeight: 1.5 }}>
        {PORCE_TX('rodape_tagline', 'Transformando ideias em peças que permanecem.')}<br />{PORCE_TX('rodape_info', 'Joinville · SC · (47) 3025-4400')}
      </div>
      <a href={`https://wa.me/${PORCE_DATA.WHATS}?text=${encodeURIComponent('Olá, Porceville! Tenho uma dúvida.')}`} onClick={() => PORCE_PING('rodape', '🟢 Visitante clicou em Tirar dúvidas no WhatsApp (rodapé)')} target="_blank" rel="noopener noreferrer"
        className="btn btn-ghost btn-sm" style={{ marginTop: 12, gap: 8, textDecoration: 'none', color: 'var(--green)' }}>
        <PIcon name="whats" size={16} stroke="var(--green)" /> Tirar dúvidas no WhatsApp
      </a>
      {app && (
        <div style={{ marginTop: 16 }}>
          <button onClick={app.openAdmin} style={{ border: 'none', background: 'none', cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--ink-mute)', fontSize: 11.5, fontWeight: 700 }}>
            <PIcon name="lock" size={13} stroke="var(--ink-mute)" /> Área comercial
          </button>
        </div>
      )}
    </div>
  );
}

// ============ Histórico de orçamentos ============
function PorceHistoryScreen({ app }) {
  return (
    <div className="scroll" style={{ paddingBottom: 28 }}>
      <PorceHeader title="Enviados" />
      {app.sent.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '52px 30px' }}>
          <div style={{ width: 74, height: 74, borderRadius: '50%', background: 'var(--porc-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
            <PIcon name="clock" size={32} stroke="var(--ink-mute)" />
          </div>
          <div className="h2">Nenhum orçamento enviado</div>
          <p className="muted" style={{ fontSize: 14, margin: '8px auto 0', maxWidth: 250, lineHeight: 1.5 }}>
            Os orçamentos que você enviar pelo WhatsApp aparecem aqui.
          </p>
        </div>
      ) : (
        <div style={{ padding: '4px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {app.sent.map(o => (
            <div key={o.id} className="card" style={{ padding: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--navy)' }}>Orçamento #{o.id}</div>
                <span className="chip-soft" style={{ padding: '4px 10px', borderRadius: 8, fontSize: 11.5 }}>Aguardando retorno</span>
              </div>
              <div className="muted" style={{ fontSize: 13, lineHeight: 1.5 }}>{o.summary}</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 }}>
                <span className="muted" style={{ fontSize: 12 }}>{o.when}</span>
                <span style={{ fontSize: 12.5, fontWeight: 800, color: 'var(--navy)' }}>{o.pieces} peças</span>
              </div>
            </div>
          ))}
        </div>
      )}
      <PorceFooter app={app} />
    </div>
  );
}

Object.assign(window, { PorceQuoteScreen, PorceHistoryScreen, PorceHeader, PorceFooter, buildWhatsMessage });
