// Pagos screens — "Pagos" tab + Factura detail
// Relies on window.loadBilling / saveBilling, facturaSaldo, facturaEstado, etc.

const ESTADO_META = {
  'por-pagar':     { label: 'Por pagar',    color: 'oklch(0.55 0.05 75)',  bg: 'oklch(0.94 0.01 75)' },
  'pago-pendiente':{ label: 'Verificando',  color: 'oklch(0.55 0.14 75)',  bg: 'oklch(0.95 0.06 85)' },
  'abonada':       { label: 'Abonada',      color: 'oklch(0.52 0.14 155)', bg: 'oklch(0.94 0.06 155)' },
  'vencida':       { label: 'Vencida',      color: 'oklch(0.5 0.18 25)',   bg: 'oklch(0.94 0.07 25)' },
  'pagada':        { label: 'Pagada',       color: 'oklch(0.48 0.14 155)', bg: 'oklch(0.94 0.06 155)' },
  'retirado':      { label: 'Retirado',     color: T_or('inkMute'),        bg: T_or('paperAlt') },
};
function T_or(k) { return (window.T && window.T[k]) || '#888'; }

function PagosTab({ vendedora, onOpenFactura }) {
  const T = window.T;
  const { Icon } = window;
  const billing = window.useBilling
    ? window.useBilling(vendedora?.id)
    : { state: window.loadBilling(), loading: false };
  const state = billing.state;
  const facturas = state.facturas;
  const pagos = state.pagos;

  if (billing.loading && facturas.length === 0) {
    return (
      <div style={{ width:'100%', minHeight:'100%', background: T.paper, padding:'80px 24px', textAlign:'center' }}>
        <div style={{ fontFamily: T.serif, fontStyle:'italic', fontSize:18, color: T.inkMute }}>Cargando facturas…</div>
      </div>
    );
  }

  const deuda = window.totalDeuda(facturas, pagos);
  const vencida = window.totalDeudaVencida(facturas, pagos);
  const proximoPago = (() => {
    const upcoming = [];
    facturas.forEach(f => {
      const saldo = window.facturaSaldo(f, pagos);
      if (saldo <= 0.01) return;
      f.cuotas.forEach(c => {
        if (c.status !== 'pagada' && new Date(c.fecha) >= new Date()) upcoming.push({ fecha: c.fecha, monto: c.monto });
      });
    });
    upcoming.sort((a, b) => new Date(a.fecha) - new Date(b.fecha));
    return upcoming[0];
  })();

  const sortedFac = [...facturas].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));

  return (
    <div style={{ width: '100%', minHeight: '100%', background: T.paper, paddingBottom: 120 }}>
      {/* Header */}
      <div style={{ padding: '58px 24px 8px' }}>
        <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: T.inkMute }}>
          Mis Facturas
        </div>
        <div style={{ fontFamily: T.serif, fontSize: 34, lineHeight: 1, color: T.ink, letterSpacing: -0.8, marginTop: 8 }}>
          Pagos
        </div>
      </div>

      {/* Deuda hero */}
      <div style={{ padding: '20px 24px 8px' }}>
        <div style={{
          background: deuda > 0 ? 'oklch(0.42 0.18 25)' : T.ink,
          color: '#fff', borderRadius: 24, padding: 24,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.6, textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 6 }}>
            {deuda > 0 ? 'Debes' : 'Estás al día'}
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 72, lineHeight: 0.9, letterSpacing: -3 }}>
            ${deuda.toFixed(2)}
          </div>
          {vencida > 0 && (
            <div style={{
              marginTop: 12, display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '6px 12px', borderRadius: 999,
              background: 'rgba(0,0,0,0.25)',
              fontFamily: T.sans, fontSize: 12,
            }}>
              <Icon name="clock" size={12} color="#fff" /> ${vencida.toFixed(2)} vencido
            </div>
          )}
          {proximoPago && deuda > 0 && (
            <div style={{
              marginTop: vencida > 0 ? 8 : 14,
              fontFamily: T.sans, fontSize: 13, color: 'rgba(255,255,255,0.75)',
            }}>
              Próxima cuota {window.fmtDate(proximoPago.fecha)} · {window.fmtMoney(proximoPago.monto)}
            </div>
          )}
        </div>
      </div>

      {/* Empresa contact */}
      {deuda > 0 && (
        <div style={{ padding: '16px 24px 8px' }}>
          <div style={{
            borderRadius: 16, padding: 14,
            background: T.paperAlt, border: `1px solid ${T.hairline}`,
          }}>
            <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 6 }}>
              Datos para pagar
            </div>
            <div style={{ display: 'flex', gap: 14 }}>
              <InfoRow label="Pago Móvil" value="0412-333-4455" />
              <InfoRow label="Banco" value="Banesco" />
              <InfoRow label="RIF" value="J-30445566-7" />
            </div>
          </div>
        </div>
      )}

      {/* Facturas list */}
      <div style={{ padding: '20px 0 0' }}>
        <window.SectionHead eyebrow="Facturas" title={`${facturas.length} activa${facturas.length === 1 ? '' : 's'}`} />
        <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sortedFac.length === 0 ? (
            <div style={{
              padding: 32, textAlign: 'center',
              fontFamily: T.serif, fontStyle: 'italic', fontSize: 16, color: T.inkMute,
            }}>
              Aún no tienes facturas.<br/>Arma tu primer pedido.
            </div>
          ) : sortedFac.map(f => {
            const saldo = window.facturaSaldo(f, pagos);
            const estado = window.facturaEstado(f, pagos);
            const meta = ESTADO_META[estado] || ESTADO_META['por-pagar'];
            const pct = Math.round((1 - Math.max(0, saldo) / f.aPagar) * 100);
            const camp = state.campaigns.find(c => c.id === f.campaignId);
            return (
              <button key={f.id} onClick={() => onOpenFactura(f)} style={{
                width: '100%', padding: 16, borderRadius: 18,
                background: T.paperAlt, border: `1px solid ${T.hairline}`,
                cursor: 'pointer', textAlign: 'left',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div>
                    <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1, color: T.inkMute }}>
                      {camp?.nombre || f.campaignId} · {f.id.slice(-5)}
                    </div>
                    <div style={{ fontFamily: T.serif, fontSize: 22, color: T.ink, letterSpacing: -0.4, marginTop: 2, lineHeight: 1 }}>
                      {saldo > 0.01 ? `Debes ${window.fmtMoney(saldo)}` : 'Pagada ✓'}
                    </div>
                    <div style={{ fontFamily: T.sans, fontSize: 11, color: T.inkSoft, marginTop: 2 }}>
                      de {window.fmtMoney(f.aPagar)} · ganancia {window.fmtMoney(f.ganancia)}
                    </div>
                  </div>
                  <span style={{
                    padding: '4px 10px', borderRadius: 999,
                    background: meta.bg, color: meta.color,
                    fontFamily: T.sans, fontSize: 10, fontWeight: 500,
                  }}>{meta.label}</span>
                </div>

                {/* Progress bar */}
                <div style={{ height: 4, background: T.hairline, borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: `${pct}%`, height: '100%', background: estado === 'vencida' ? 'oklch(0.55 0.18 25)' : T.accent, transition: 'width 0.5s' }} />
                </div>

                {/* Cuotas dots */}
                <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
                  {f.cuotas.map((c, i) => (
                    <CuotaDot key={i} cuota={c} />
                  ))}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function InfoRow({ label, value }) {
  const T = window.T;
  return (
    <div style={{ flex: 1 }}>
      <div style={{ fontFamily: T.mono, fontSize: 9, color: T.inkMute, letterSpacing: 0.5 }}>{label}</div>
      <div style={{ fontFamily: T.sans, fontSize: 13, color: T.ink, marginTop: 2, fontWeight: 500 }}>{value}</div>
    </div>
  );
}

function CuotaDot({ cuota }) {
  const T = window.T;
  const isPagada = cuota.status === 'pagada';
  const now = new Date();
  const isVencida = !isPagada && new Date(cuota.fecha) < now;
  const bg = isPagada ? 'oklch(0.6 0.14 155)' : isVencida ? 'oklch(0.55 0.18 25)' : T.hairlineStrong;
  return (
    <div style={{
      flex: 1, padding: '6px 8px', borderRadius: 8,
      background: T.paper, border: `1px solid ${T.hairline}`,
      display: 'flex', alignItems: 'center', gap: 6,
    }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: bg }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: T.mono, fontSize: 9, color: T.inkMute }}>
          {window.fmtDate(cuota.fecha)}
        </div>
        <div style={{ fontFamily: T.sans, fontSize: 10, color: T.ink }}>
          ${cuota.monto.toFixed(2)}
        </div>
      </div>
    </div>
  );
}

// ——— Factura detail ———
function FacturaDetail({ factura, vendedora, onClose, onRegistrarPago }) {
  const T = window.T;
  const { Icon } = window;
  const billing = window.useBilling
    ? window.useBilling(vendedora?.id)
    : { state: window.loadBilling(), loading: false };
  const state = billing.state;
  const pagos = state.pagos.filter(p => p.facturaId === factura.id);
  const saldo = window.facturaSaldo(factura, pagos);
  const estado = window.facturaEstado(factura, pagos);
  const meta = ESTADO_META[estado] || ESTADO_META['por-pagar'];
  const camp = state.campaigns.find(c => c.id === factura.campaignId);

  const pagoStatusColor = (s) =>
    s === 'verificado' ? 'oklch(0.5 0.14 155)'
    : s === 'rechazado' ? 'oklch(0.55 0.18 25)'
    : 'oklch(0.55 0.14 75)';

  return (
    <div style={{ width: '100%', minHeight: '100%', background: T.paper, paddingBottom: 120 }}>
      {/* Top bar */}
      <div style={{ padding: '58px 20px 8px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onClose} style={{
          width: 38, height: 38, 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>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, color: T.inkMute }}>
            {camp?.nombre || factura.campaignId}
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 20, color: T.ink, letterSpacing: -0.3 }}>
            Factura {factura.id.slice(-5)}
          </div>
        </div>
      </div>

      {/* Hero saldo */}
      <div style={{ padding: '8px 24px 16px' }}>
        <div style={{
          background: saldo > 0.01 ? (estado === 'vencida' ? 'oklch(0.42 0.18 25)' : T.ink) : 'oklch(0.45 0.14 155)',
          color: '#fff', borderRadius: 22, padding: 22,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{
              padding: '3px 9px', borderRadius: 999, background: 'rgba(255,255,255,0.2)',
              fontFamily: T.sans, fontSize: 10, letterSpacing: 0.5,
            }}>{meta.label}</span>
          </div>
          <div style={{ fontFamily: T.mono, fontSize: 10, letterSpacing: 1.4, textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginTop: 8 }}>
            {saldo > 0.01 ? 'Saldo pendiente' : 'Pagado completo'}
          </div>
          <div style={{ fontFamily: T.serif, fontSize: 56, lineHeight: 0.95, letterSpacing: -2.5, marginTop: 2 }}>
            ${Math.max(0, saldo).toFixed(2)}
          </div>

          {factura.retiroCodigo && (
            <div style={{
              marginTop: 16, padding: 14, borderRadius: 14,
              background: 'rgba(0,0,0,0.25)',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: 10, background: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name="check" size={24} color={T.ink} />
              </div>
              <div>
                <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1, color: 'rgba(255,255,255,0.7)' }}>
                  Código de retiro
                </div>
                <div style={{ fontFamily: T.mono, fontSize: 18, color: '#fff', fontWeight: 500, letterSpacing: 0.5, marginTop: 1 }}>
                  {factura.retiroCodigo}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Desglose */}
      <div style={{ padding: '0 24px 16px' }}>
        <div style={{
          borderRadius: 16, padding: 16,
          background: T.paperAlt, border: `1px solid ${T.hairline}`,
        }}>
          <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: 1.4, textTransform: 'uppercase', color: T.inkMute, marginBottom: 10 }}>
            Desglose
          </div>
          <Row label="Total del pedido" value={window.fmtMoney(factura.total)} />
          <Row label={`Tu ganancia (${factura.descuentoPct}%)`} value={`− ${window.fmtMoney(factura.ganancia)}`} accent />
          <div style={{ borderTop: `1px solid ${T.hairline}`, margin: '10px 0' }} />
          <Row label="A pagar a empresa" value={window.fmtMoney(factura.aPagar)} bold />
        </div>
      </div>

      {/* Cuotas */}
      <div>
        <window.SectionHead eyebrow="Fechas de pago" title="3 cuotas" />
        <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {factura.cuotas.map((c, i) => {
            const isPagada = c.status === 'pagada';
            const isVencida = !isPagada && new Date(c.fecha) < new Date();
            return (
              <div key={i} style={{
                padding: 14, borderRadius: 14,
                background: T.paperAlt, border: `1px solid ${isVencida ? 'oklch(0.55 0.18 25 / 0.3)' : T.hairline}`,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10,
                  background: isPagada ? 'oklch(0.94 0.06 155)' : isVencida ? 'oklch(0.94 0.07 25)' : T.paper,
                  color: isPagada ? 'oklch(0.4 0.14 155)' : isVencida ? 'oklch(0.5 0.18 25)' : T.ink,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: T.serif, fontSize: 18,
                }}>
                  {isPagada ? '✓' : i + 1}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: T.serif, fontSize: 17, color: T.ink, letterSpacing: -0.2, lineHeight: 1 }}>
                    {window.fmtMoney(c.monto)}
                  </div>
                  <div style={{ fontFamily: T.sans, fontSize: 12, color: T.inkSoft, marginTop: 2 }}>
                    {new Date(c.fecha).toLocaleDateString('es', { weekday: 'short', day: 'numeric', month: 'long' })}
                  </div>
                </div>
                <span style={{
                  fontFamily: T.sans, fontSize: 10, padding: '3px 9px', borderRadius: 999,
                  background: isPagada ? 'oklch(0.94 0.06 155)' : isVencida ? 'oklch(0.94 0.07 25)' : T.paper,
                  color: isPagada ? 'oklch(0.4 0.14 155)' : isVencida ? 'oklch(0.5 0.18 25)' : T.inkMute,
                  border: `1px solid ${T.hairline}`,
                }}>
                  {isPagada ? 'Pagada' : isVencida ? 'Vencida' : 'Próxima'}
                </span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Pagos registrados */}
      {pagos.length > 0 && (
        <div style={{ marginTop: 20 }}>
          <window.SectionHead eyebrow="Tus pagos" title={`${pagos.length} registrado${pagos.length === 1 ? '' : 's'}`} />
          <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 8 }}>
            {pagos.slice().sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)).map(p => (
              <div key={p.id} style={{
                padding: 14, borderRadius: 14,
                background: T.paperAlt, border: `1px solid ${T.hairline}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                  <div style={{ fontFamily: T.serif, fontSize: 20, color: T.ink, letterSpacing: -0.3 }}>
                    {window.fmtMoney(p.monto)}
                  </div>
                  <span style={{
                    fontFamily: T.sans, fontSize: 10, padding: '3px 9px', borderRadius: 999,
                    background: p.status === 'verificado' ? 'oklch(0.94 0.06 155)'
                      : p.status === 'rechazado' ? 'oklch(0.94 0.07 25)' : 'oklch(0.95 0.06 85)',
                    color: pagoStatusColor(p.status),
                  }}>
                    {p.status === 'verificado' ? '✓ Verificado' : p.status === 'rechazado' ? 'Rechazado' : 'Verificando…'}
                  </span>
                </div>
                <div style={{ fontFamily: T.sans, fontSize: 12, color: T.inkSoft }}>
                  {p.metodo}{p.banco ? ` · ${p.banco}` : ''}{p.referencia ? ` · Ref ${p.referencia}` : ''}
                </div>
                <div style={{ fontFamily: T.mono, fontSize: 10, color: T.inkMute, marginTop: 3 }}>
                  {window.fmtDate(p.fecha)} · {new Date(p.createdAt).toLocaleDateString('es', { day: '2-digit', month: 'short' })}
                </div>
                {p.rejectReason && (
                  <div style={{ marginTop: 6, fontFamily: T.sans, fontSize: 11, color: 'oklch(0.5 0.18 25)' }}>
                    Razón: {p.rejectReason}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Register payment button */}
      {saldo > 0.01 && (
        <div style={{
          position: 'fixed', left: '50%', transform: 'translateX(-50%)',
          bottom: 80, zIndex: 10, width: 'calc(100% - 48px)', maxWidth: 350,
        }}>
          <button onClick={() => onRegistrarPago(factura)} style={{
            width: '100%', padding: 16, borderRadius: 999,
            background: T.accent, color: '#fff', border: 'none', cursor: 'pointer',
            fontFamily: T.sans, fontSize: 14, fontWeight: 500,
            boxShadow: '0 14px 30px rgba(0,0,0,0.2)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}>
            + Registrar pago
          </button>
        </div>
      )}
    </div>
  );
}

function Row({ label, value, accent, bold }) {
  const T = window.T;
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '3px 0' }}>
      <span style={{ fontFamily: T.sans, fontSize: bold ? 14 : 13, color: accent ? T.accent : bold ? T.ink : T.inkSoft, fontWeight: bold ? 500 : 400 }}>
        {label}
      </span>
      <span style={{ fontFamily: bold ? T.serif : T.sans, fontSize: bold ? 22 : 14, color: accent ? T.accent : T.ink, letterSpacing: bold ? -0.3 : 0 }}>
        {value}
      </span>
    </div>
  );
}

Object.assign(window, { PagosTab, FacturaDetail });
