/* PORCEVILLE — Captura de contato + gravação do pedido (mobile + desktop).
   Abre antes de mandar pro WhatsApp: registra o lead no painel admin (Supabase)
   e dispara o WhatsApp. Se o Supabase não estiver configurado, só dispara o WhatsApp
   (comportamento equivalente ao antigo, sem perder nada). */

async function porceSaveOrder(order) {
  const cfg = window.PORCE_CFG || {};
  if (!cfg.url || !cfg.anonKey) return { saved: false };
  try {
    const r = await fetch(`${cfg.url}/rest/v1/orders`, {
      method: 'POST',
      headers: {
        apikey: cfg.anonKey, Authorization: 'Bearer ' + cfg.anonKey,
        'Content-Type': 'application/json', Prefer: 'return=minimal',
        'Content-Profile': (cfg.schema || 'porceville'),
      },
      body: JSON.stringify(order),
    });
    return { saved: r.ok, status: r.status };
  } catch (e) { return { saved: false, error: e.message }; }
}

/* Captura de um Pedido (ver CONTEXT.md — Pedido, não Sinal de intenção: sempre tem contato real).
   Grava em orders, notifica /api/lead e rastreia generate_lead atrás de 1 interface só — os 3
   formulários que capturam contato (orçamento, "Não achou o que precisa?", popup de cupom) usavam
   essa sequência reimplementada à mão e já tinham divergido (o popup ignorava se o save falhava).
   Retorna { saved }, resolvido depois do INSERT no banco; notificação e rastreio são melhor-esforço
   (fire-and-forget com keepalive, sobrevivem à navegação pro WhatsApp) e não afetam o retorno. */
async function porceCaptureLead({ customer_name, customer_phone, customer_email, source, items, pieces, summary }) {
  const r = await porceSaveOrder({
    customer_name, customer_phone, customer_email: customer_email || null,
    source, items: items || [], pieces: pieces || 0, total: null, status: 'novo',
  });
  try {
    fetch('/api/lead', { method: 'POST', keepalive: true, headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name: customer_name, phone: customer_phone, email: customer_email || null, pieces: pieces || 0, summary: summary || '', items: items || [] }) });
  } catch (e) {}
  try { window.PORCE_TRACK && PORCE_TRACK('generate_lead', { source, pieces: pieces || 0 }); } catch (e) {}
  return { saved: !!(r && r.saved) };
}

function OrderCaptureModal({ app }) {
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const valid = name.trim().length >= 2 && phone.replace(/\D/g, '').length >= 10;

  const [done, setDone] = React.useState(false);
  const [pieces, setPieces] = React.useState(0);
  const [summary, setSummary] = React.useState('');
  const [waUrl, setWaUrl] = React.useState('');

  const submit = async () => {
    if (!valid || busy) return;
    setBusy(true);
    const quote = app.quote;
    const pc = quote.reduce((s, e) => s + e.qty, 0);
    const items = quote.map(e => ({
      product_id: e.productId, name: e.name, qty: e.qty,
      size: e.size || null, piece: e.piece || null, colors: e.colors || null,
      engraving: (typeof engravingLabel === 'function') ? engravingLabel(e) : null,
    }));
    const source = (typeof window !== 'undefined' && window.innerWidth >= 980) ? 'desktop' : 'mobile';
    const sm = quote.map(e => `${e.qty}× ${e.name}`).join(' · ');

    // grava + notifica + rastreia atrás de 1 interface só (porceCaptureLead)
    await porceCaptureLead({
      customer_name: name.trim(), customer_phone: phone.trim(),
      customer_email: email.trim() || null, source, items, pieces: pc, summary: sm,
    });

    // monta o link do WhatsApp com a lista do pedido + dados do cliente (cumpre o "Enviar pelo WhatsApp")
    const greet = `Olá, Porceville! Sou ${name.trim()} (${phone.trim()}). Gostaria de um orçamento:`;
    const lines = (typeof buildWhatsMessage === 'function')
      ? decodeURIComponent(buildWhatsMessage(quote)).replace(/^Olá, Porceville![^\n]*\n\n/, '').replace(/\n\nAguardo[\s\S]*$/, '')
      : quote.map(e => `• ${e.qty}× ${e.name}`).join('\n');
    const text = encodeURIComponent(`${greet}\n\n${lines}\n\nAguardo o retorno. Obrigado!`);
    setWaUrl(`https://wa.me/${PORCE_DATA.WHATS}?text=${text}`);

    setPieces(pc); setSummary(sm); setBusy(false); setDone(true);
  };

  const finish = () => app.commitSent({ pieces, summary });

  if (done) {
    return (
      <>
        <div className="overlay" onClick={finish} />
        <div className="sheet" style={{ height: 'auto', paddingBottom: 30, maxWidth: 460, margin: '0 auto', left: 0, right: 0 }}>
          <div className="sheet-grip" />
          <div style={{ padding: '14px 24px 0', textAlign: 'center' }}>
            <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--green)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
              <PIcon name="check" size={30} stroke="#fff" sw={2.4} />
            </div>
            <div className="h2">Pedido recebido! ✨</div>
            <p className="muted" style={{ fontSize: 14, margin: '8px auto 4px', maxWidth: 300, lineHeight: 1.55 }}>
              Obrigado, <b style={{ color: 'var(--navy)' }}>{name.trim().split(' ')[0]}</b>! Nossa equipe vai te chamar no WhatsApp/telefone em breve com os valores e prazos.
            </p>
            <p className="muted" style={{ fontSize: 12.5, margin: '0 auto 18px' }}>{pieces} peças · sem compromisso</p>
            {waUrl && (
              <a className="btn btn-whats btn-block" href={waUrl} target="_blank" rel="noopener noreferrer" style={{ padding: 15, marginBottom: 8 }} onClick={() => setTimeout(finish, 400)}>
                <PIcon name="whats" size={19} stroke="#fff" /> Abrir conversa no WhatsApp
              </a>
            )}
            <button className="btn btn-ghost btn-block" style={{ padding: 15 }} onClick={finish}>Continuar navegando</button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <div className="overlay" onClick={app.cancelSend} />
      <div className="sheet" style={{ height: 'auto', paddingBottom: 28, maxWidth: 460, margin: '0 auto', left: 0, right: 0 }}>
        <div className="sheet-grip" />
        <div style={{ padding: '6px 22px 0' }}>
          <div className="h2" style={{ marginBottom: 2 }}>Finalize seu pedido</div>
          <p className="muted" style={{ fontSize: 13.5, margin: '4px 0 16px', lineHeight: 1.5 }}>
            Deixe seu contato — nossa equipe retorna com os valores e prazos. Sem compromisso.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
            <input className="porce-input" placeholder="Seu nome *" value={name} onChange={e => setName(e.target.value)} autoFocus />
            <input className="porce-input" placeholder="WhatsApp / telefone *" value={phone} onChange={e => setPhone(e.target.value)} inputMode="tel" />
            <input className="porce-input" placeholder="E-mail (opcional)" value={email} onChange={e => setEmail(e.target.value)} inputMode="email" />
          </div>
          <button className="btn btn-navy btn-block" style={{ marginTop: 16, padding: 15, fontSize: 15.5, opacity: valid && !busy ? 1 : .5 }}
            disabled={!valid || busy} onClick={submit}>
            <PIcon name="check" size={19} stroke="#fff" /> {busy ? 'Enviando…' : 'Enviar pedido'}
          </button>
          <button className="btn btn-ghost btn-block" style={{ marginTop: 8 }} onClick={app.cancelSend}>Voltar</button>
        </div>
      </div>
      <style>{`.porce-input{width:100%;box-sizing:border-box;padding:13px 14px;border:1.5px solid var(--line);border-radius:12px;font-size:15px;font-family:var(--font-body);color:var(--ink);background:var(--surface);outline:none}.porce-input:focus{border-color:var(--navy)}`}</style>
    </>
  );
}

Object.assign(window, { OrderCaptureModal, porceSaveOrder, porceCaptureLead });
