// Order detail + confirmation flow with inline WhatsApp composer
function OrderDetailScreen({ pedido, onClose, onMarkEnviado, onMarkCompletado, onDownload, onSendWA, onOpenFactura }) {
  const T = window.T;
  const { Icon, ProductTile, StatusPill } = window;
  const [mode, setMode] = React.useState('detail'); // detail | confirm | whatsapp
  const [waNumber, setWaNumber] = React.useState('');

  const total = pedido.productos.reduce((s, x) => s + x.precio * x.cantidad, 0);
  const items = pedido.productos.reduce((s, x) => s + x.cantidad, 0);

  // Look up the factura created for this pedido (matched by pedidoId)
  // Lee facturas de Supabase vía useBilling, con fallback a loadBilling local
  const billing = window.useBilling
    ? window.useBilling(pedido?.vendedoraId || (pedido && pedido._remote ? null : null))
    : { state: { facturas: [] }, loading: false };
  const factura = React.useMemo(() => {
    try {
      const list = billing.state.facturas;
      const local = list.find(f => f.pedidoId === pedido.id || f.pedidoId === pedido.codigo);
      if (local) return local;
      // fallback a loadBilling local
      const st = window.loadBilling ? window.loadBilling() : { facturas: [] };
      return st.facturas.find(f => f.pedidoId === pedido.id || f.pedidoId === pedido.codigo) || null;
    } catch { return null; }
  }, [pedido]);

  // Timeline steps
  const steps = [
    { key: 'creado', label: 'Creado', done: true, time: pedido.fechaCreacion },
    { key: 'enviado', label: 'Enviado a sistema', done: pedido.enviado, time: pedido.enviado ? pedido.fechaCreacion : null },
    { key: 'completado', label: 'Completado', done: pedido.estado === 'completado', time: pedido.fechaEntrega || null },
  ];

  const message = React.useMemo(() => (
    `Hola Inovabot, pedido listo.\n\n` +
    `*Pedido ${pedido.codigo}*\n` +
    `Vendedora: ${pedido.vendedora || 'María Pérez'} · ${pedido.zona || 'Valencia'}\n\n` +
    `*Productos:*\n` +
    pedido.productos.map(p => `• ${p.nombre} (${p.catalogo}) x${p.cantidad} — $${(p.precio * p.cantidad).toFixed(2)}`).join('\n') +
    `\n\n*Total: $${total.toFixed(2)}*`
  ), [pedido, total]);

  return (
    <div style={{ width: '100%', height: '100%', background: T.paper, display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '58px 24px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 999, background: T.paperAlt,
          border: `1px solid ${T.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Icon name="close" size={16} color={T.ink} /></button>
        <StatusPill estado={pedido.estado} enviado={pedido.enviado} size="sm" />
        <button style={{
          width: 36, height: 36, borderRadius: 999, background: T.paperAlt,
          border: `1px solid ${T.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Icon name="doc" size={14} color={T.ink} /></button>
      </div>

      {/* Title block */}
      <div style={{ padding: '14px 24px 18px' }}>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, color: T.inkMute, marginBottom: 6 }}>
          {pedido.codigo}
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 56, lineHeight: 0.95, color: T.ink, letterSpacing: -2 }}>
          ${total.toFixed(2)}
        </div>
        <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 18, color: T.inkSoft, marginTop: 6, letterSpacing: -0.2 }}>
          {items} ítems · {pedido.fechaCreacion.toLocaleDateString('es', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' })}
        </div>
      </div>

      {/* Body scroll */}
      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 140 }}>
        {/* Factura banner */}
        {factura && (
          <div style={{ padding: '0 24px 20px' }}>
            <button onClick={() => onOpenFactura && onOpenFactura(factura)} style={{
              width: '100%', padding: 16, borderRadius: 18,
              background: T.accentSoft, border: `1px solid ${T.accent}33`,
              cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12, background: T.paper,
                border: `1px solid ${T.accent}55`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: T.serif, fontSize: 22, color: T.accent, letterSpacing: -0.3,
              }}>$</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: T.accentInk, opacity: 0.7 }}>
                  Factura · {factura.campaignId} · {factura.id.slice(-5)}
                </div>
                <div style={{ fontFamily: T.serif, fontSize: 18, color: T.accentInk, letterSpacing: -0.3, marginTop: 2 }}>
                  Debes ${factura.aPagar.toFixed(2)} a la empresa
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 11, color: T.accentInk, opacity: 0.75, marginTop: 2 }}>
                  Tu ganancia: ${factura.ganancia.toFixed(2)} · 3 cuotas · Tocar para pagar
                </div>
              </div>
              <Icon name="chevronR" size={16} color={T.accent} />
            </button>
          </div>
        )}

        {/* Timeline */}
        <div style={{ padding: '0 24px 24px' }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 14 }}>
            Estado
          </div>
          <div style={{ position: 'relative', paddingLeft: 22 }}>
            <div style={{ position: 'absolute', left: 5, top: 6, bottom: 6, width: 1, background: T.hairline }} />
            {steps.map((s, i) => (
              <div key={s.key} style={{ position: 'relative', marginBottom: i < steps.length - 1 ? 14 : 0 }}>
                <div style={{
                  position: 'absolute', left: -22, top: 3, width: 11, height: 11, borderRadius: 999,
                  background: s.done ? T.accent : T.paper,
                  border: `1.5px solid ${s.done ? T.accent : T.hairlineStrong}`,
                }} />
                <div style={{ fontFamily: T.serif, fontSize: 16, color: s.done ? T.ink : T.inkMute, letterSpacing: -0.2, lineHeight: 1.1 }}>
                  {s.label}
                </div>
                {s.time && (
                  <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, marginTop: 2, letterSpacing: 0.5 }}>
                    {s.time.toLocaleDateString('es', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Products */}
        <div style={{ padding: '0 24px 24px' }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 12 }}>
            {pedido.productos.length} productos
          </div>
          <div style={{ background: T.paperAlt, borderRadius: 18, border: `1px solid ${T.hairline}`, overflow: 'hidden' }}>
            {pedido.productos.map((p, i) => (
              <div key={p.id || i} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
                borderTop: i > 0 ? `1px solid ${T.hairline}` : 'none',
              }}>
                <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={40} radius={8} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontFamily: T.mono, fontSize: 9, color: T.inkMute, letterSpacing: 0.5, marginBottom: 2 }}>
                    {p.codigo} · {p.catalogo}
                  </div>
                  <div style={{ fontFamily: T.serif, fontSize: 14, color: T.ink, lineHeight: 1.15, letterSpacing: -0.1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {p.nombre}
                  </div>
                  <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkSoft, marginTop: 2 }}>
                    ${p.precio.toFixed(2)} × {p.cantidad}
                  </div>
                </div>
                <div style={{ fontFamily: T.serif, fontSize: 16, color: T.ink, letterSpacing: -0.2 }}>
                  ${(p.precio * p.cantidad).toFixed(2)}
                </div>
              </div>
            ))}
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '14px 16px', background: T.paper, borderTop: `1px solid ${T.hairline}`,
            }}>
              <span style={{ fontFamily: T.sans, fontSize: 13, color: T.inkSoft, fontWeight: 500 }}>Total</span>
              <span style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, letterSpacing: -0.3 }}>${total.toFixed(2)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom action bar */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 20px 28px',
        background: `linear-gradient(180deg, rgba(255,253,248,0) 0%, ${T.paper} 40%)`,
        display: 'flex', gap: 8,
      }}>
        <button onClick={onDownload} style={{
          flex: 1, padding: '14px 12px', borderRadius: 999,
          background: T.paperAlt, color: T.ink, border: `1px solid ${T.hairline}`,
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          fontFamily: T.sans, fontSize: 13, fontWeight: 500,
        }}>
          <Icon name="doc" size={14} color={T.ink} /> PDF
        </button>
        <button onClick={() => setMode('whatsapp')} style={{
          flex: 2, padding: '14px 18px', borderRadius: 999,
          background: T.ink, color: T.paper, border: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontFamily: T.sans, fontSize: 14, fontWeight: 500,
        }}>
          <Icon name="send" size={14} color={T.paper} /> Enviar por WhatsApp
        </button>
      </div>

      {/* WhatsApp composer sheet */}
      {mode === 'whatsapp' && (
        <div style={{
          position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.35)',
          display: 'flex', alignItems: 'flex-end', zIndex: 30,
        }} onClick={() => setMode('detail')}>
          <div onClick={(e) => e.stopPropagation()} style={{
            width: '100%', background: T.paper, borderRadius: '28px 28px 0 0',
            padding: '12px 24px 32px', maxHeight: '82%', overflow: 'auto',
          }}>
            <div style={{ width: 40, height: 4, background: T.hairlineStrong, borderRadius: 999, margin: '4px auto 18px' }} />

            <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 6 }}>
              Paso final
            </div>
            <div style={{ fontFamily: T.serif, fontSize: 26, color: T.ink, letterSpacing: -0.5, lineHeight: 1.1, marginBottom: 20 }}>
              Enviar por WhatsApp
            </div>

            {/* message preview */}
            <div style={{
              background: T.paperAlt, borderRadius: 14, padding: 14,
              fontFamily: T.mono, fontSize: 11, color: T.ink, lineHeight: 1.55,
              whiteSpace: 'pre-wrap', border: `1px solid ${T.hairline}`,
              maxHeight: 160, overflow: 'auto', marginBottom: 18,
            }}>{message}</div>

            <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 8 }}>
              Número destino
            </div>
            <input
              value={waNumber} onChange={(e) => setWaNumber(e.target.value.replace(/\D/g, ''))}
              placeholder="04121234567"
              style={{
                width: '100%', padding: '14px 16px', borderRadius: 14,
                border: `1px solid ${T.hairline}`, background: T.paper,
                fontFamily: T.mono, fontSize: 14, letterSpacing: 1, color: T.ink,
                outline: 'none', boxSizing: 'border-box', marginBottom: 10,
              }}
            />
            <div style={{ display: 'flex', gap: 6, marginBottom: 20, flexWrap: 'wrap' }}>
              {['04141234567', '04126655432'].map(n => (
                <button key={n} onClick={() => setWaNumber(n)} style={{
                  padding: '6px 10px', borderRadius: 999, border: `1px solid ${T.hairline}`,
                  background: T.paperAlt, color: T.inkSoft,
                  fontFamily: T.mono, fontSize: 11, cursor: 'pointer',
                }}>{n}</button>
              ))}
            </div>

            <window.PrimaryBtn
              disabled={waNumber.length < 10}
              onClick={() => { onSendWA && onSendWA(pedido.id); setMode('detail'); }}
              icon={<Icon name="send" size={14} color={waNumber.length < 10 ? T.inkMute : T.paper} />}
            >
              Abrir WhatsApp
            </window.PrimaryBtn>
          </div>
        </div>
      )}
    </div>
  );
}

// Confirmation screen shown when creating a NEW order
function ConfirmCreateScreen({ draft, vendedora, onConfirm, onBack }) {
  const T = window.T;
  const { Icon, ProductTile } = window;
  const total = draft.reduce((s, p) => s + p.precio * p.cantidad, 0);
  const items = draft.reduce((s, p) => s + p.cantidad, 0);
  const [sending, setSending] = React.useState(false);

  const handleConfirm = () => {
    setSending(true);
    setTimeout(() => onConfirm(), 500);
  };

  return (
    <div style={{ width: '100%', height: '100%', background: T.paper, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '58px 24px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 999, background: T.paperAlt,
          border: `1px solid ${T.hairline}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><Icon name="chevronL" size={16} color={T.ink} /></button>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute }}>
          Confirmar
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div style={{ padding: '24px 24px 24px' }}>
        <div style={{ fontFamily: T.serif, fontSize: 38, lineHeight: 1, color: T.ink, letterSpacing: -1 }}>
          Revisa tu
        </div>
        <div style={{ fontFamily: T.serif, fontStyle: 'italic', fontSize: 38, lineHeight: 1.05, color: T.accent, letterSpacing: -1 }}>
          pedido.
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 24px', paddingBottom: 140 }}>
        {/* vendedora card */}
        <div style={{
          background: T.paperAlt, borderRadius: 18, padding: 16, marginBottom: 16,
          border: `1px solid ${T.hairline}`,
        }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 8 }}>
            Vendedora
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 18, color: T.ink, letterSpacing: -0.2 }}>
            {vendedora?.nombre || 'María Pérez'}
          </div>
          <div style={{ fontFamily: T.sans, fontSize: 13, color: T.inkSoft, marginTop: 2 }}>
            {vendedora?.zona} · {vendedora?.telefono}
          </div>
        </div>

        {/* products */}
        <div style={{ background: T.paperAlt, borderRadius: 18, border: `1px solid ${T.hairline}`, overflow: 'hidden', marginBottom: 16 }}>
          {draft.map((p, i) => (
            <div key={p.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
              borderTop: i > 0 ? `1px solid ${T.hairline}` : 'none',
            }}>
              <ProductTile tono={p.tono} catalogo={p.catalogo} imagen={p.imagen} size={40} radius={8} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: T.serif, fontSize: 14, color: T.ink, letterSpacing: -0.1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {p.nombre}
                </div>
                <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, letterSpacing: 0.5, marginTop: 2 }}>
                  {p.codigo} · {p.catalogo} · ×{p.cantidad}
                </div>
              </div>
              <div style={{ fontFamily: T.serif, fontSize: 15, color: T.ink }}>
                ${(p.precio * p.cantidad).toFixed(2)}
              </div>
            </div>
          ))}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 16px', background: T.paper, borderTop: `1px solid ${T.hairline}`,
          }}>
            <span style={{ fontFamily: T.sans, fontSize: 13, color: T.inkSoft }}>Total · {items} ítems</span>
            <span style={{ fontFamily: T.serif, fontSize: 24, color: T.ink, letterSpacing: -0.4 }}>${total.toFixed(2)}</span>
          </div>
        </div>

        {/* verify notice */}
        <div style={{
          background: T.accentSoft, borderRadius: 14, padding: '14px 16px',
          display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <Icon name="info" size={16} color={T.accent} style={{ marginTop: 2, flexShrink: 0 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.accentInk, fontWeight: 500, marginBottom: 2 }}>
              Verifica los códigos.
            </div>
            <div style={{ fontFamily: T.sans, fontSize: 12, color: T.accentInk, opacity: 0.8, lineHeight: 1.4 }}>
              Los errores en código son responsabilidad de la vendedora.
            </div>
          </div>
        </div>
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, padding: '12px 20px 28px',
        background: `linear-gradient(180deg, rgba(255,253,248,0) 0%, ${T.paper} 40%)`,
      }}>
        <window.PrimaryBtn
          onClick={handleConfirm}
          disabled={sending}
          icon={!sending && <Icon name="check" size={16} color={T.paper} />}
        >
          {sending ? 'Confirmando…' : `Confirmar pedido · $${total.toFixed(2)}`}
        </window.PrimaryBtn>
      </div>
    </div>
  );
}

Object.assign(window, { OrderDetailScreen, ConfirmCreateScreen });
