/* ============================================================
   wizard_steps_a.jsx — Etapas 1, 2, 3
   ============================================================ */

/* ===== ETAPA 1 — Cadastro ===== */
function StepCadastro({ cliente, setCliente }) {
  const upd = (k) => (e) => setCliente({ ...cliente, [k]: e.target.value });
  const updMask = (k, fn) => (e) => setCliente({ ...cliente, [k]: fn(e.target.value) });
  return (
    <div className="step-pane fade-up">
      <header className="step-head">
        <Badge tone="blue" dot>Etapa 1 de 6</Badge>
        <h1>Dados do cliente</h1>
        <p>Cadastre as informações de contato para iniciar a proposta comercial.</p>
      </header>
      <div className="form-card">
        <div className="form-grid">
          <Field full label="Nome completo" icon="user" name="nome" placeholder="Ex.: Maria Oliveira"
            value={cliente.nome} onChange={upd('nome')} autoFocus />
          <Field label="Empresa" icon="building" name="empresa" placeholder="Razão social / fantasia"
            value={cliente.empresa} onChange={upd('empresa')} />
          <Field label="CPF / CNPJ" icon="doc" name="doc" placeholder="000.000.000-00"
            value={cliente.doc} onChange={updMask('doc', maskDoc)} inputMode="numeric" />
          <Field label="WhatsApp" icon="whatsapp" name="whatsapp" placeholder="(11) 90000-0000"
            value={cliente.whatsapp} onChange={updMask('whatsapp', maskPhone)} inputMode="tel" />
          <Field label="E-mail" icon="mail" name="email" type="email" placeholder="contato@empresa.com"
            value={cliente.email} onChange={upd('email')} />
          <Field full label="Endereço" icon="pin" name="endereco" placeholder="Rua, nº, bairro — Cidade/UF"
            value={cliente.endereco} onChange={upd('endereco')} />
        </div>
      </div>
    </div>
  );
}

/* ===== ETAPA 2 — Seleção de Serviços ===== */
function ServiceCard({ svc, selected, item, onToggle, onEdit }) {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => { if (!selected) setOpen(false); }, [selected]);
  return (
    <div className={'svc-card' + (selected ? ' is-sel' : '')}>
      <div className="svc-top" onClick={() => onToggle(svc)}>
        <div className="svc-check">{selected ? <Icon name="check" size={15} stroke={3} /> : <Icon name="plus" size={15} stroke={2.4} />}</div>
        <div className="grow" style={{ minWidth: 0 }}>
          <div className="row gap-2" style={{ marginBottom: 3 }}>
            <span className="svc-cat">{svc.cat}</span>
            {svc.tipo === 'recorrente' && <span className="svc-rec">mensal</span>}
          </div>
          <h4 className="svc-name">{svc.nome}</h4>
          <p className="svc-desc">{svc.desc}</p>
        </div>
      </div>
      <div className="svc-foot">
        <div className="col" style={{ gap: 0 }}>
          <span className="svc-price mono">{fmtBRL(selected ? item.preco : svc.preco)}</span>
          <span style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{selected ? item.prazo : svc.prazo}</span>
        </div>
        {selected ? (
          <button className="svc-edit" onClick={() => setOpen(o => !o)}>
            <Icon name="edit" size={14} /> Editar
          </button>
        ) : (
          <button className="svc-add" onClick={() => onToggle(svc)}>Adicionar</button>
        )}
      </div>
      {selected && open && (
        <div className="svc-editor fade-up">
          <div className="svc-editor-grid">
            <Field label="Valor (R$)">
              <input type="number" min="0" step="10" value={item.preco}
                onChange={(e) => onEdit(svc.id, { preco: Number(e.target.value) })}
                style={{ background: 'none', border: 'none', outline: 'none', flex: 1, padding: '13px 0', fontSize: 15 }} />
            </Field>
            <Field label="Prazo contratual">
              <input type="text" value={item.prazo}
                onChange={(e) => onEdit(svc.id, { prazo: e.target.value })}
                style={{ background: 'none', border: 'none', outline: 'none', flex: 1, padding: '13px 0', fontSize: 15 }} />
            </Field>
          </div>
          <Field label="Observações">
            <textarea rows="2" value={item.obs} placeholder="Escopo, entregáveis, condições específicas…"
              onChange={(e) => onEdit(svc.id, { obs: e.target.value })}
              style={{ background: 'none', border: 'none', outline: 'none', flex: 1, padding: '11px 0', fontSize: 14, resize: 'vertical' }} />
          </Field>
        </div>
      )}
    </div>
  );
}

function StepServicos({ items, toggleService, editItem, removeItem, total, recorrente, cliente, onAdvance }) {
  const [cat, setCat] = React.useState('Todos');
  const cats = ['Todos', ...Array.from(new Set(SERVICES.map(s => s.cat)))];
  const byId = Object.fromEntries(items.map(i => [i.id, i]));
  const list = cat === 'Todos' ? SERVICES : SERVICES.filter(s => s.cat === cat);
  return (
    <div className="step-pane svc-pane fade-up">
      <div className="svc-main">
        <header className="step-head">
          <Badge tone="blue" dot>Etapa 2 de 6</Badge>
          <h1>Monte a proposta</h1>
          <p>Selecione os serviços, ajuste valores, prazos e observações conforme a negociação.</p>
        </header>
        <div className="cat-tabs">
          {cats.map(c => (
            <button key={c} className={'cat-tab' + (c === cat ? ' on' : '')} onClick={() => setCat(c)}>{c}</button>
          ))}
        </div>
        <div className="svc-grid">
          {list.map(svc => (
            <ServiceCard key={svc.id} svc={svc} selected={!!byId[svc.id]} item={byId[svc.id]}
              onToggle={toggleService} onEdit={editItem} />
          ))}
        </div>
      </div>
      <CartSidebar items={items} total={total} recorrente={recorrente}
        onRemove={removeItem} onAdvance={onAdvance} cliente={cliente} />

      {items.length > 0 && (
        <div className="mob-checkout">
          <div className="col" style={{ gap: 0, lineHeight: 1.15 }}>
            <span style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{items.length} {items.length === 1 ? 'item' : 'itens'}</span>
            <span className="mono" style={{ fontSize: 19, fontWeight: 700, fontFamily: 'var(--font-display)' }}>{fmtBRL(total)}</span>
          </div>
          <Button size="lg" iconR="arrowR" onClick={onAdvance}>Continuar</Button>
        </div>
      )}
    </div>
  );
}

/* ===== ETAPA 3 — Resumo ===== */
function SummaryRow({ label, value, strong, align = 'right' }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline', gap: 16, padding: '11px 0', borderBottom: '1px solid var(--line)' }}>
      <span style={{ color: 'var(--text-3)', fontSize: 13.5, flexShrink: 0 }}>{label}</span>
      <span style={{ fontWeight: strong ? 700 : 500, fontSize: 14, textAlign: align, maxWidth: '64%', overflowWrap: 'anywhere' }}>{value || '—'}</span>
    </div>
  );
}

function StepResumo({ cliente, items, total, recorrente, pagamento, setPagamento, obsGeral, setObsGeral }) {
  return (
    <div className="step-pane narrow fade-up">
      <header className="step-head">
        <Badge tone="blue" dot>Etapa 3 de 6</Badge>
        <h1>Resumo da contratação</h1>
        <p>Revise os dados antes de gerar o termo de aceite.</p>
      </header>
      <div className="summary-grid">
        <section className="panel">
          <div className="panel-h"><Icon name="user" size={16} /> Dados do cliente</div>
          <SummaryRow label="Nome" value={cliente.nome} />
          <SummaryRow label="Empresa" value={cliente.empresa} />
          <SummaryRow label="CPF/CNPJ" value={cliente.doc} />
          <SummaryRow label="WhatsApp" value={cliente.whatsapp} />
          <SummaryRow label="E-mail" value={cliente.email} align="left" />
          <SummaryRow label="Endereço" value={cliente.endereco} />
        </section>

        <section className="panel">
          <div className="panel-h"><Icon name="cart" size={16} /> Serviços contratados</div>
          <div className="sum-items">
            {items.map(it => (
              <div key={it.id} className="sum-item">
                <div className="grow">
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{it.nome}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-3)' }}>
                    Prazo: {it.prazo}{it.tipo === 'recorrente' ? ' · recorrente' : ''}
                  </div>
                  {it.obs && <div className="sum-obs">“{it.obs}”</div>}
                </div>
                <span className="mono" style={{ fontWeight: 600 }}>{fmtBRL(it.preco)}</span>
              </div>
            ))}
          </div>
          <div className="sum-total">
            {recorrente > 0 && (
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 13, color: 'var(--text-2)', marginBottom: 6 }}>
                <span>Recorrente / mês</span><span className="mono">{fmtBRL(recorrente)}</span>
              </div>
            )}
            <div className="row" style={{ justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontWeight: 600 }}>Valor total</span>
              <span className="mono" style={{ fontSize: 28, fontWeight: 700, fontFamily: 'var(--font-display)', color: 'var(--brand-yellow)' }}>{fmtBRL(total)}</span>
            </div>
          </div>
        </section>

        <section className="panel">
          <div className="panel-h"><Icon name="money" size={16} /> Forma de pagamento</div>
          <div className="pay-opts">
            {PAYMENT_METHODS.map(m => (
              <button key={m.id} className={'pay-opt' + (pagamento === m.id ? ' on' : '')} onClick={() => setPagamento(m.id)}>
                <span className="pay-radio" />{m.nome}
              </button>
            ))}
          </div>
        </section>

        <section className="panel">
          <div className="panel-h"><Icon name="edit" size={16} /> Observações gerais</div>
          <textarea className="obs-area" rows="4" value={obsGeral} onChange={(e) => setObsGeral(e.target.value)}
            placeholder="Condições comerciais, descontos, prazos de início, etc." />
        </section>
      </div>
    </div>
  );
}

Object.assign(window, { StepCadastro, StepServicos, StepResumo });
