/* ============================================================
   wizard_parts.jsx — Cart, QRCode, Stepper, shared step bits
   ============================================================ */

/* ---------- QR Code (usa global qrcode-generator) ---------- */
function QRCode({ text, size = 220 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    try {
      const qr = window.qrcode(0, 'M');
      qr.addData(text);
      qr.make();
      const count = qr.getModuleCount();
      const cell = Math.floor(size / count);
      ref.current.innerHTML = qr.createSvgTag({ cellSize: cell, margin: 0, scalable: true });
      const svg = ref.current.querySelector('svg');
      if (svg) { svg.style.width = size + 'px'; svg.style.height = size + 'px'; svg.style.display = 'block'; }
    } catch (e) { ref.current.innerHTML = '<div style="color:#888;font-size:12px">QR indisponível</div>'; }
  }, [text, size]);
  return <div ref={ref} style={{ background: '#fff', padding: 14, borderRadius: 14, lineHeight: 0 }} />;
}

/* ---------- Stepper (topo do wizard) ---------- */
const STEPS = [
  { n: 1, label: 'Cadastro',      icon: 'user' },
  { n: 2, label: 'Serviços',      icon: 'cart' },
  { n: 3, label: 'Resumo',        icon: 'doc' },
  { n: 4, label: 'Aceite',        icon: 'check' },
  { n: 5, label: 'Compartilhar',  icon: 'send' },
  { n: 6, label: 'Pagamento',     icon: 'qr' },
];

function Stepper({ step, maxStep, onJump }) {
  return (
    <div className="stepper-wrap">
      <div className="stepper">
        {STEPS.map((s, i) => {
          const done = s.n < step;
          const active = s.n === step;
          const reachable = s.n <= maxStep;
          return (
            <React.Fragment key={s.n}>
              <button
                className="step-node" data-active={active} data-done={done}
                disabled={!reachable}
                onClick={() => reachable && onJump(s.n)}
                style={{ cursor: reachable ? 'pointer' : 'not-allowed' }}>
                <span className="step-dot">
                  {done ? <Icon name="check" size={16} stroke={2.6} /> : <Icon name={s.icon} size={16} />}
                </span>
                <span className="step-label">{s.label}</span>
              </button>
              {i < STEPS.length - 1 && <span className="step-line" data-done={s.n < step} />}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Cart sidebar (Etapa 2) ---------- */
function CartSidebar({ items, total, recorrente, onRemove, onAdvance, cliente }) {
  const empty = items.length === 0;
  return (
    <aside className="cart">
      <div className="row gap-3" style={{ justifyContent: 'space-between', marginBottom: 4 }}>
        <div className="row gap-2">
          <Icon name="cart" size={18} style={{ color: 'var(--brand-yellow)' }} />
          <h3 style={{ fontSize: 16 }}>Resumo</h3>
        </div>
        <Badge tone="gray">{items.length} {items.length === 1 ? 'item' : 'itens'}</Badge>
      </div>
      {cliente?.nome && (
        <div className="cart-client">
          <span className="eyebrow" style={{ fontSize: 10 }}>Cliente</span>
          <div style={{ fontWeight: 600, fontSize: 14 }}>{cliente.nome}</div>
          {cliente.empresa && <div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>{cliente.empresa}</div>}
        </div>
      )}
      <div className="cart-items">
        {empty && (
          <div className="cart-empty">
            <Icon name="cart" size={26} style={{ color: 'var(--text-dim)' }} />
            <span>Selecione serviços ao lado para montar a proposta.</span>
          </div>
        )}
        {items.map((it) => (
          <div key={it.id} className="cart-item fade-up">
            <div className="grow" style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.nome}</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{it.prazo}{it.tipo === 'recorrente' ? ' · recorrente' : ''}</div>
            </div>
            <div className="col" style={{ alignItems: 'flex-end', gap: 2 }}>
              <span className="mono" style={{ fontSize: 13.5, fontWeight: 600 }}>{fmtBRL(it.preco)}</span>
              <button className="cart-x" onClick={() => onRemove(it.id)} title="Remover"><Icon name="x" size={13} /></button>
            </div>
          </div>
        ))}
      </div>
      <div className="cart-foot">
        {recorrente > 0 && (
          <div className="row" style={{ justifyContent: 'space-between', fontSize: 13, color: 'var(--text-2)' }}>
            <span>Recorrente / mês</span>
            <span className="mono">{fmtBRL(recorrente)}</span>
          </div>
        )}
        <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <span style={{ fontSize: 13, color: 'var(--text-2)' }}>Total</span>
          <span className="mono" style={{ fontSize: 26, fontWeight: 700, fontFamily: 'var(--font-display)' }}>{fmtBRL(total)}</span>
        </div>
        <Button full size="lg" disabled={empty} onClick={onAdvance} iconR="arrowR"
          style={empty ? { opacity: .4, pointerEvents: 'none' } : {}}>
          Continuar
        </Button>
      </div>
    </aside>
  );
}

Object.assign(window, { QRCode, Stepper, CartSidebar, STEPS });
