// Product modal · drafts drawer · checkout · WhatsApp send

const { useState: useStateQ, useMemo: useMemoQ, useEffect: useEffectQ, useRef: useRefQ } = React;

const SIX = {
  whatsapp: "5551993848020", // (51) 99384-8020
  whatsappFmt: "(51) 99384-8020",
  empresa: "Six Revestimentos de Alto Padrão",
  endereco: "Av. Serraria 1490, Loja 3 — Guarujá, Porto Alegre/RS",
  cnpj: "43.296.534/0001-10",
};

const FINALIDADES = window.FINALIDADES;
const AMBIENTES = window.AMBIENTES;
const TIPO_OBRA = window.TIPO_OBRA;
const TIPO_CLIENTE = window.TIPO_CLIENTE;
const PAGAMENTO = ["6x sem juros", "À vista (Pix/dinheiro) — me consultem desconto", "Cartão à vista", "Boleto/Faturado", "Não definido"];

// — utility —
const fmtCEP = (v) => v.replace(/\D/g,'').slice(0,8).replace(/(\d{5})(\d)/, '$1-$2');
const fmtWA  = (v) => {
  const d = v.replace(/\D/g,'').slice(0,11);
  if (d.length <= 2) return d ? `(${d}` : '';
  if (d.length <= 6) return `(${d.slice(0,2)}) ${d.slice(2)}`;
  if (d.length <= 10) return `(${d.slice(0,2)}) ${d.slice(2,6)}-${d.slice(6)}`;
  return `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
};
const fmtCPFCNPJ = (v) => {
  const d = v.replace(/\D/g,'').slice(0,14);
  if (d.length <= 11) {
    return d.replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d)/, '.$1-$2');
  }
  return d.replace(/(\d{2})(\d)/, '$1.$2').replace(/(\d{2})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d)/, '.$1/$2').replace(/(\d{4})(\d)/, '$1-$2');
};
const moneyBR = (n) => n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });

// — caixa estimator: derive m² per box from formato —
const m2PerBox = (product) => {
  // rough heuristic based on product
  if (product.pattern === "organic" || /org/.test(product.formato[0])) return 0.5; // caixa de 0,5m² (pedras orgânicas)
  if (product.pattern === "brick" || product.pattern === "rockface") return 0.42;
  if (product.pattern === "mosaic") return 0.46;
  if (product.pattern === "stripes" || product.pattern === "filetes") return 0.45;
  return 0.5;
};

// — Product Configuration Page (substitui o catálogo enquanto está aberto) —
const ProductPage = ({ product, onClose, onAddDraft, savedDefaults }) => {
  const p = product;
  const [formato, setFormato] = useStateQ(p.formato[0]);
  const [m2, setM2] = useStateQ(savedDefaults.m2 || '');
  const [margem, setMargem] = useStateQ(10);
  const [finalidade, setFinalidade] = useStateQ(FINALIDADES[0]);
  const [ambiente, setAmbiente] = useStateQ('');
  const [ambienteOutro, setAmbienteOutro] = useStateQ('');
  const [tipoObra, setTipoObra] = useStateQ('');
  const [cep, setCep] = useStateQ(savedDefaults.cep || '');
  const [prazo, setPrazo] = useStateQ('');
  const [comArgamassa, setComArgamassa] = useStateQ('nao');
  const [temProjeto, setTemProjeto] = useStateQ('nao');
  const [pagamento, setPagamento] = useStateQ(PAGAMENTO[0]);
  const [amostraFisica, setAmostraFisica] = useStateQ(false);
  const [obs, setObs] = useStateQ('');
  const [ambientView, setAmbientView] = useStateQ(0);

  const m2n = parseFloat((m2 || '').toString().replace(',','.')) || 0;
  const totalM2 = m2n * (1 + margem / 100);
  const caixas = Math.ceil(totalM2 / m2PerBox(p));
  const totalEstimado = totalM2 * p.precoM2;

  const cepValid = cep.replace(/\D/g,'').length === 8;
  const canAdd = m2n > 0 && ambiente && tipoObra && cepValid && prazo;

  // close on Esc → volta ao catálogo
  useEffectQ(() => {
    const onKey = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    // Scroll to top when entering product page
    window.scrollTo({ top: 0, behavior: 'instant' });
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose, product?.id]);

  const handleAdd = () => {
    onAddDraft({
      product: p,
      config: {
        formato,
        m2: m2n,
        margem,
        totalM2: parseFloat(totalM2.toFixed(2)),
        caixas,
        precoEstimado: parseFloat(totalEstimado.toFixed(2)),
        finalidade,
        ambiente,
        ambienteOutro: ambiente === 'Outro' ? ambienteOutro : '',
        tipoObra,
        cep: fmtCEP(cep),
        prazo,
        comArgamassa,
        temProjeto,
        pagamento,
        amostraFisica,
        obs: obs.trim(),
        createdAt: Date.now(),
      }
    });
  };

  return (
    <div className="product-page">
      <div className="product-page__bar">
        <button className="product-page__back" onClick={onClose}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
          Voltar ao catálogo
        </button>
        <nav className="product-page__crumbs">
          <a onClick={onClose}>Catálogo</a>
          <span>›</span>
          <a onClick={onClose}>{p.categoria}</a>
          <span>›</span>
          <span className="is-current">{p.nome}</span>
        </nav>
      </div>
      <div className="product-page__body">

        <div className="pm__gallery">
          <div className="pm__hero">
            {(() => {
              const views = [p.image, ...(p.ambients || [])].filter(Boolean);
              if (views.length > 0) {
                const idx = Math.min(ambientView, views.length - 1);
                return <img src={views[idx]} alt={p.nome} className="pm__hero-img" />;
              }
              return ambientView === 0
                ? <Texture product={p} seed={11} density={0.9} w={600} h={600} />
                : <AmbientShot product={p} variant={ambientView - 1} />;
            })()}
          </div>
          <div className="pm__thumbs">
            {(() => {
              const views = [p.image, ...(p.ambients || [])].filter(Boolean);
              if (views.length > 0) {
                return views.slice(0, 4).map((src, i) => (
                  <button key={i} className={"pm__thumb" + (ambientView === i ? " is-active" : "")} onClick={()=>setAmbientView(i)}>
                    <img src={src} alt="" className="pm__thumb-img"/>
                  </button>
                ));
              }
              return (
                <>
                  <button className={"pm__thumb" + (ambientView === 0 ? " is-active" : "")} onClick={()=>setAmbientView(0)}>
                    <Texture product={p} seed={11} density={1} w={120} h={120} />
                  </button>
                  {[0,1,2].map(i => (
                    <button key={i} className={"pm__thumb" + (ambientView === i+1 ? " is-active" : "")} onClick={()=>setAmbientView(i+1)}>
                      <AmbientShot product={p} variant={i} />
                    </button>
                  ))}
                </>
              );
            })()}
          </div>
          <div className="pm__palette">
            <span className="pm__palette-label">Paleta</span>
            {p.paleta.map((c,i) => <span key={i} className="pm__swatch" style={{background:c}} />)}
          </div>
        </div>

        <div className="pm__panel">
          <div className="pm__head">
            <div className="pm__crumb">{p.categoria}</div>
            <h2 className="pm__name">{p.nome}</h2>
            <p className="pm__desc">{p.desc}</p>
            <div className="pm__price-row">
              <div className="pm__price">
                <span className="pm__price-faixa">{p.faixaPreco}</span>
                <span className="pm__price-sub">/m² · em até {p.parcelas}x sem juros</span>
              </div>
              <span className="pm__pro">
                <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z"/></svg>
                PRO: arquiteto? Solicite desconto profissional
              </span>
            </div>
          </div>

          <hr className="pm__divider"/>

          <div className="pm__form">
            <FormRow label="Formato da peça" required>
              <div className="seg">
                {p.formato.map(f => (
                  <button key={f} className={"seg__opt" + (formato === f ? " seg__opt--on" : "")} onClick={()=>setFormato(f)}>{f}</button>
                ))}
              </div>
            </FormRow>

            <FormRow label="Metragem (m²)" required hint="Quantos m² de área você precisa cobrir?">
              <input
                type="text"
                inputMode="decimal"
                className="inp inp--big"
                value={m2}
                onChange={e=>setM2(e.target.value.replace(/[^\d,.]/g, ''))}
                placeholder="ex: 12,5"
              />
              <span className="inp__suffix">m²</span>
            </FormRow>

            <FormRow label="Margem de quebra" hint="Recomendamos 10% para pedras naturais — perda por corte/ajuste.">
              <div className="seg">
                {[0,5,10,15].map(m => (
                  <button key={m} className={"seg__opt" + (margem === m ? " seg__opt--on" : "")} onClick={()=>setMargem(m)}>+{m}%</button>
                ))}
              </div>
              {margem < 10 && m2n > 0 && (
                <div className="warn">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                  Para esta peça sugerimos pelo menos 10% de margem.
                </div>
              )}
            </FormRow>

            {m2n > 0 && (
              <div className="calc">
                <div className="calc__row">
                  <span>Metragem base</span><strong>{m2n.toLocaleString('pt-BR')} m²</strong>
                </div>
                <div className="calc__row">
                  <span>Com {margem}% de quebra</span><strong>{totalM2.toLocaleString('pt-BR', {maximumFractionDigits: 2})} m²</strong>
                </div>
                <div className="calc__row">
                  <span>Caixas necessárias <em>(≈{m2PerBox(p)} m²/cx)</em></span><strong>{caixas} {caixas === 1 ? 'caixa' : 'caixas'}</strong>
                </div>
                <div className="calc__row calc__row--total">
                  <span>Estimativa total <em>(sob cotação)</em></span><strong>{moneyBR(totalEstimado)}</strong>
                </div>
              </div>
            )}

            <FormRow label="Finalidade" required>
              <div className="seg seg--wrap">
                {FINALIDADES.map(f => (
                  <button key={f} className={"seg__opt" + (finalidade === f ? " seg__opt--on" : "")} onClick={()=>setFinalidade(f)}>{f}</button>
                ))}
              </div>
            </FormRow>

            <FormRow label="Ambiente" required>
              <select className="inp" value={ambiente} onChange={e=>setAmbiente(e.target.value)}>
                <option value="">Selecione um ambiente…</option>
                {AMBIENTES.map(a => <option key={a} value={a}>{a}</option>)}
              </select>
              {ambiente === 'Outro' && (
                <input type="text" className="inp" placeholder="Descreva o ambiente…" value={ambienteOutro} onChange={e=>setAmbienteOutro(e.target.value)} style={{marginTop:8}}/>
              )}
            </FormRow>

            <FormRow label="Tipo de obra" required>
              <div className="seg seg--wrap">
                {TIPO_OBRA.map(t => (
                  <button key={t} className={"seg__opt" + (tipoObra === t ? " seg__opt--on" : "")} onClick={()=>setTipoObra(t)}>{t}</button>
                ))}
              </div>
            </FormRow>

            <div className="form-grid form-grid--2">
              <FormRow label="CEP de entrega" required>
                <input
                  type="text"
                  className="inp"
                  value={cep}
                  onChange={e => setCep(fmtCEP(e.target.value))}
                  placeholder="00000-000"
                />
                {cepValid && (
                  <div className="hint hint--ok">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6L9 17l-5-5"/></svg>
                    Frete estimado: <strong>3–5 dias úteis</strong> via transportadora SIX
                  </div>
                )}
              </FormRow>

              <FormRow label="Prazo desejado" required>
                <select className="inp" value={prazo} onChange={e=>setPrazo(e.target.value)}>
                  <option value="">Quando precisa receber?</option>
                  <option>Urgente — até 7 dias</option>
                  <option>Até 15 dias</option>
                  <option>Até 30 dias</option>
                  <option>Até 60 dias</option>
                  <option>Sem pressa / orçando ainda</option>
                </select>
              </FormRow>
            </div>

            <FormRow label="Levar argamassa / rejunte junto?">
              <div className="seg">
                <button className={"seg__opt" + (comArgamassa === 'sim' ? " seg__opt--on" : "")} onClick={()=>setComArgamassa('sim')}>Sim, recomendem</button>
                <button className={"seg__opt" + (comArgamassa === 'so-argamassa' ? " seg__opt--on" : "")} onClick={()=>setComArgamassa('so-argamassa')}>Só argamassa</button>
                <button className={"seg__opt" + (comArgamassa === 'so-rejunte' ? " seg__opt--on" : "")} onClick={()=>setComArgamassa('so-rejunte')}>Só rejunte</button>
                <button className={"seg__opt" + (comArgamassa === 'nao' ? " seg__opt--on" : "")} onClick={()=>setComArgamassa('nao')}>Não, já tenho</button>
              </div>
            </FormRow>

            <FormRow label="Tem projeto pronto ou arquiteto envolvido?">
              <div className="seg">
                <button className={"seg__opt" + (temProjeto === 'sim' ? " seg__opt--on" : "")} onClick={()=>setTemProjeto('sim')}>Sim, projeto definido</button>
                <button className={"seg__opt" + (temProjeto === 'estudo' ? " seg__opt--on" : "")} onClick={()=>setTemProjeto('estudo')}>Em estudo</button>
                <button className={"seg__opt" + (temProjeto === 'nao' ? " seg__opt--on" : "")} onClick={()=>setTemProjeto('nao')}>Sou o proprietário, sem arquiteto</button>
              </div>
            </FormRow>

            <FormRow label="Forma de pagamento preferida">
              <select className="inp" value={pagamento} onChange={e=>setPagamento(e.target.value)}>
                {PAGAMENTO.map(p => <option key={p}>{p}</option>)}
              </select>
            </FormRow>

            <FormRow label="">
              <label className="check">
                <input type="checkbox" checked={amostraFisica} onChange={e=>setAmostraFisica(e.target.checked)} />
                <span>Quero receber uma <strong>amostra física grátis</strong> antes de fechar (válido para pedidos a partir de 8m²).</span>
              </label>
            </FormRow>

            <FormRow label="Observações livres">
              <textarea
                className="inp inp--ta"
                rows={3}
                placeholder="Detalhes do projeto, paginação desejada, dúvidas técnicas…"
                value={obs}
                onChange={e=>setObs(e.target.value)}
              />
            </FormRow>
          </div>

          <div className="pm__footer">
            <button className="btn btn--ghost" onClick={onClose}>Cancelar</button>
            <button className={"btn btn--primary" + (!canAdd ? " btn--disabled" : "")} disabled={!canAdd} onClick={handleAdd}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>
              Adicionar aos meus orçamentos
            </button>
          </div>
          {!canAdd && (m2 || ambiente || cep || prazo) && (
            <div className="pm__footer-note">Preencha m², ambiente, tipo de obra, CEP e prazo para continuar.</div>
          )}
        </div>
      </div>
    </div>
  );
};

const FormRow = ({ label, required, hint, children }) => (
  <div className="row">
    {label && (
      <label className="row__label">
        {label}{required && <span className="row__req">*</span>}
      </label>
    )}
    <div className="row__field">{children}</div>
    {hint && <div className="row__hint">{hint}</div>}
  </div>
);

// — Drafts drawer —
const PedidosDrawer = ({ open, onClose, pedidos, onEdit, onDelete, onSend, savedClient }) => {
  return (
    <>
      <div className={"drawer-scrim" + (open ? " is-open" : "")} onClick={onClose} />
      <aside className={"drawer" + (open ? " drawer--open" : "")} aria-hidden={!open}>
        <header className="drawer__head">
          <div>
            <div className="drawer__title">Meus orçamentos</div>
            <div className="drawer__sub">{pedidos.length} {pedidos.length === 1 ? 'pedido pronto' : 'pedidos prontos'} para enviar</div>
          </div>
          <button className="modal__close" onClick={onClose} aria-label="Fechar">×</button>
        </header>

        <div className="drawer__info">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><circle cx="12" cy="16" r="0.5" fill="currentColor"/></svg>
          <span>Cada produto vira <strong>1 orçamento independente</strong> no WhatsApp da Six — assim cada peça recebe atenção dedicada e proposta separada.</span>
        </div>

        <div className="drawer__body">
          {pedidos.length === 0 ? (
            <div className="drawer__empty">
              <div className="drawer__empty-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1"><path d="M3 7h18M5 7l1 13h12l1-13M9 11v6M15 11v6"/></svg>
              </div>
              <div>Nenhum orçamento ainda.</div>
              <small>Escolha um revestimento no catálogo para começar.</small>
            </div>
          ) : (
            pedidos.map((ped, idx) => (
              <PedidoCard
                key={ped.id}
                pedido={ped}
                index={idx+1}
                onEdit={() => onEdit(ped)}
                onDelete={() => onDelete(ped.id)}
                onSend={() => onSend(ped)}
              />
            ))
          )}
        </div>

        {pedidos.length > 0 && (
          <footer className="drawer__foot">
            <div className="drawer__foot-info">
              <div className="drawer__foot-line"><span>Subtotal estimado</span><strong>{moneyBR(pedidos.reduce((s,p) => s + (p.config.precoEstimado || 0), 0))}</strong></div>
              <div className="drawer__foot-line drawer__foot-line--mute"><span>Valores finais sob cotação após análise da Six.</span></div>
            </div>
            <button className="btn btn--ghost btn--wide" onClick={() => onSend('all')}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="10"/><path d="M16.5 11.5c-.5 1.5-2.5 4-4.5 4s-4-2.5-4.5-4M12 7v2M9.5 7.5l.5 1M14.5 7.5l-.5 1"/></svg>
              Enviar TODOS por WhatsApp ({pedidos.length})
            </button>
          </footer>
        )}
      </aside>
    </>
  );
};

const PedidoCard = ({ pedido, index, onEdit, onDelete, onSend }) => {
  const p = pedido.product;
  const c = pedido.config;
  return (
    <div className="pedido">
      <div className="pedido__head">
        <div className="pedido__num">Orçamento #{String(index).padStart(2, '0')}</div>
        <button className="pedido__del" onClick={onDelete} aria-label="Remover">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M8 6V4h8v2M6 6l1 14h10l1-14M10 11v6M14 11v6"/></svg>
        </button>
      </div>
      <div className="pedido__body">
        <div className="pedido__thumb">
          {p.image ? <img src={p.image} alt={p.nome} className="pedido__thumb-img"/> : <Texture product={p} seed={p.id.length+1} density={1.2} w={120} h={120} />}
        </div>
        <div className="pedido__info">
          <div className="pedido__cat">{p.categoria}</div>
          <div className="pedido__name">{p.nome}</div>
          <div className="pedido__chips">
            <span className="pedido__chip">{c.formato}</span>
            <span className="pedido__chip">{c.totalM2.toLocaleString('pt-BR', {maximumFractionDigits:2})} m²</span>
            <span className="pedido__chip">{c.caixas} cx</span>
            <span className="pedido__chip">{c.ambiente}{c.ambienteOutro && ` · ${c.ambienteOutro}`}</span>
          </div>
          <div className="pedido__details">
            <div><b>Finalidade:</b> {c.finalidade}</div>
            <div><b>Obra:</b> {c.tipoObra}</div>
            <div><b>CEP:</b> {c.cep} · <b>Prazo:</b> {c.prazo}</div>
          </div>
          <div className="pedido__est">
            Estimativa: <strong>{moneyBR(c.precoEstimado)}</strong> <em>(sob cotação)</em>
          </div>
        </div>
      </div>
      <div className="pedido__actions">
        <button className="btn btn--ghost btn--sm" onClick={onEdit}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M12 20h9M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z"/></svg>
          Editar
        </button>
        <button className="btn btn--wa btn--sm" onClick={onSend}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.2-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6 0-.3-.2-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.2-.6-1.5-.8-2-.2-.5-.4-.4-.6-.4-.2 0-.4 0-.5 0s-.4 0-.7.3c-.2.3-.9.9-.9 2.2 0 1.3.9 2.6 1.1 2.8.1.2 1.9 2.9 4.6 4 .6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.6-.6 1.8-1.3.2-.6.2-1.2.2-1.3-.1-.1-.3-.2-.5-.3z"/><path d="M20 12c0 4.4-3.6 8-8 8-1.5 0-2.9-.4-4.1-1.1L3 20l1.2-4.5C3.5 14.4 3 13.2 3 12c0-4.4 3.6-8 8-8s9 3.6 9 8z" stroke="currentColor" strokeWidth="1.6" fill="none"/></svg>
          Enviar #{String(index).padStart(2,'0')} no WhatsApp
        </button>
      </div>
    </div>
  );
};

// — Checkout modal: client data collection —
const CheckoutModal = ({ pedidos, onClose, onSubmit, savedClient }) => {
  // pedidos é array (1 ou todos)
  const [client, setClient] = useStateQ(savedClient || {
    nome: '', whatsapp: '', email: '', cpfcnpj: '', tipo: 'Pessoa física', empresa: '', desejaAmostra: false,
  });
  const set = (k, v) => setClient(c => ({...c, [k]: v}));

  const valid = client.nome.length > 2 && client.whatsapp.replace(/\D/g,'').length >= 10;

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal modal--checkout" onClick={e=>e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Fechar">×</button>

        <div className="ck__head">
          <div className="ck__eyebrow">ÚLTIMO PASSO</div>
          <h2 className="ck__title">Para quem a gente envia o orçamento?</h2>
          <p className="ck__sub">
            Vamos abrir o WhatsApp com {pedidos.length === 1 ? <><strong>1 orçamento</strong></> : <><strong>{pedidos.length} orçamentos</strong> — um de cada vez</>} já preenchidos, prontos para você enviar.
          </p>
        </div>

        <div className="ck__summary">
          {pedidos.map((p, i) => (
            <div key={p.id} className="ck__summary-item">
              <div className="ck__summary-thumb">{p.product.image ? <img src={p.product.image} alt="" className="ck__summary-thumb-img"/> : <Texture product={p.product} seed={i+3} density={1.4} w={60} h={60}/>}</div>
              <div>
                <div className="ck__summary-name">{p.product.nome}</div>
                <div className="ck__summary-meta">{p.config.totalM2.toLocaleString('pt-BR')} m² · {p.config.ambiente} · {p.config.cep}</div>
              </div>
              <div className="ck__summary-price">{p.product.faixaPreco}</div>
            </div>
          ))}
        </div>

        <div className="ck__form">
          <FormRow label="Tipo de cliente">
            <div className="seg seg--wrap">
              {TIPO_CLIENTE.map(t => (
                <button key={t} className={"seg__opt" + (client.tipo === t ? " seg__opt--on" : "")} onClick={()=>set('tipo', t)}>{t}</button>
              ))}
            </div>
          </FormRow>
          <FormRow label="Nome completo" required>
            <input className="inp" value={client.nome} onChange={e=>set('nome', e.target.value)} placeholder="Como podemos te chamar?"/>
          </FormRow>
          <div className="form-grid form-grid--2">
            <FormRow label="WhatsApp" required>
              <input className="inp" value={client.whatsapp} onChange={e=>set('whatsapp', fmtWA(e.target.value))} placeholder="(00) 00000-0000"/>
            </FormRow>
            <FormRow label="E-mail">
              <input className="inp" type="email" value={client.email} onChange={e=>set('email', e.target.value)} placeholder="seu@email.com"/>
            </FormRow>
          </div>
          <div className="form-grid form-grid--2">
            <FormRow label="CPF / CNPJ">
              <input className="inp" value={client.cpfcnpj} onChange={e=>set('cpfcnpj', fmtCPFCNPJ(e.target.value))} placeholder="000.000.000-00"/>
            </FormRow>
            {(client.tipo !== 'Pessoa física') && (
              <FormRow label="Empresa / Escritório">
                <input className="inp" value={client.empresa} onChange={e=>set('empresa', e.target.value)} placeholder="Nome da empresa"/>
              </FormRow>
            )}
          </div>
          {client.tipo === 'Arquiteto / designer' && (
            <div className="pro-banner">
              <div className="pro-banner__star">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3 6 7 1-5 5 1 7-6-3-6 3 1-7-5-5 7-1z"/></svg>
              </div>
              <div>
                <strong>Programa SIX PRO</strong> — você receberá condição especial para arquitetos e amostras prioritárias na sua proposta.
              </div>
            </div>
          )}
        </div>

        <div className="ck__foot">
          <button className="btn btn--ghost" onClick={onClose}>Voltar</button>
          <button
            className={"btn btn--wa btn--lg" + (!valid ? " btn--disabled" : "")}
            disabled={!valid}
            onClick={() => onSubmit(client)}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.2-1.7-.8-1.9-.9-.3-.1-.4-.1-.6.2-.2.3-.7.9-.8 1-.2.2-.3.2-.6 0-.3-.2-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.2-.6-1.5-.8-2-.2-.5-.4-.4-.6-.4-.2 0-.4 0-.5 0s-.4 0-.7.3c-.2.3-.9.9-.9 2.2 0 1.3.9 2.6 1.1 2.8.1.2 1.9 2.9 4.6 4 .6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.6-.6 1.8-1.3.2-.6.2-1.2.2-1.3-.1-.1-.3-.2-.5-.3z"/></svg>
            {pedidos.length === 1 ? 'Abrir WhatsApp e enviar' : `Enviar ${pedidos.length} orçamentos`}
          </button>
        </div>
      </div>
    </div>
  );
};

// — WhatsApp message builder —
const buildWhatsAppMessage = (pedido, index, client, total) => {
  const p = pedido.product;
  const c = pedido.config;
  const lines = [];
  lines.push(`*ORÇAMENTO ${total > 1 ? `${index}/${total}` : `#${String(index).padStart(3,'0')}`} — Six Revestimentos*`);
  lines.push('');
  lines.push(`📦 *Produto:* ${p.nome}`);
  lines.push(`🔖 Categoria: ${p.categoria}`);
  lines.push(`📐 Formato escolhido: ${c.formato}`);
  lines.push(`🎨 Acabamento: ${p.acabamento}`);
  lines.push('');
  lines.push(`*Metragem solicitada*`);
  lines.push(`• Base: ${c.m2.toLocaleString('pt-BR')} m²`);
  lines.push(`• Margem de quebra: +${c.margem}%`);
  lines.push(`• Total: ${c.totalM2.toLocaleString('pt-BR', {maximumFractionDigits:2})} m² (~${c.caixas} caixa${c.caixas>1?'s':''})`);
  lines.push(`• Estimativa: ${moneyBR(c.precoEstimado)} _(sob cotação)_`);
  lines.push('');
  lines.push(`*Aplicação*`);
  lines.push(`• Finalidade: ${c.finalidade}`);
  lines.push(`• Ambiente: ${c.ambiente}${c.ambienteOutro ? ` (${c.ambienteOutro})` : ''}`);
  lines.push(`• Tipo de obra: ${c.tipoObra}`);
  if (c.temProjeto === 'sim') lines.push(`• Projeto pronto / arquiteto envolvido`);
  else if (c.temProjeto === 'estudo') lines.push(`• Projeto em estudo`);
  if (c.comArgamassa === 'sim') lines.push(`• Incluir argamassa + rejunte sugeridos`);
  else if (c.comArgamassa === 'so-argamassa') lines.push(`• Incluir argamassa`);
  else if (c.comArgamassa === 'so-rejunte') lines.push(`• Incluir rejunte`);
  lines.push('');
  lines.push(`*Entrega & prazo*`);
  lines.push(`• CEP: ${c.cep}`);
  lines.push(`• Prazo: ${c.prazo}`);
  lines.push(`• Pagamento: ${c.pagamento}`);
  if (c.amostraFisica) lines.push(`• ✋ Solicita amostra física grátis`);
  if (c.obs) {
    lines.push('');
    lines.push(`💬 *Observações:* ${c.obs}`);
  }
  lines.push('');
  lines.push(`👤 *Cliente*`);
  lines.push(`• Nome: ${client.nome}`);
  lines.push(`• WhatsApp: ${client.whatsapp}`);
  if (client.email) lines.push(`• E-mail: ${client.email}`);
  if (client.cpfcnpj) lines.push(`• CPF/CNPJ: ${client.cpfcnpj}`);
  lines.push(`• Tipo: ${client.tipo}`);
  if (client.empresa) lines.push(`• Empresa: ${client.empresa}`);
  lines.push('');
  lines.push(`_Enviado via catálogo digital · sixmateriais.com.br_`);
  return lines.join('\n');
};

const sendToWhatsApp = (pedido, index, client, total) => {
  const msg = buildWhatsAppMessage(pedido, index, client, total);
  const url = `https://wa.me/${SIX.whatsapp}?text=${encodeURIComponent(msg)}`;
  window.open(url, '_blank', 'noopener');
};

Object.assign(window, { ProductPage, ProductModal: ProductPage, PedidosDrawer, CheckoutModal, sendToWhatsApp, buildWhatsAppMessage, SIX });
