// ─────────────────────────────────────────────────────────────
// Notifications sheet
// ─────────────────────────────────────────────────────────────
function NotificationsSheet({ open, onClose, onSign, onRequest }) {
  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 40,
        background: 'rgba(10,22,40,0.4)', backdropFilter: 'blur(4px)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .2s',
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 50,
        background: '#fff', borderRadius: '24px 24px 0 0',
        maxHeight: '78%', overflow: 'auto',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform .28s cubic-bezier(.2,.8,.3,1)',
        fontFamily: FA.sans, boxShadow: '0 -4px 30px rgba(0,0,0,0.15)',
      }}>
        <Pill/>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 20px 14px' }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: FA.ink, letterSpacing: -0.4 }}>Notificaciones</div>
            <div style={{ fontSize: 12, color: FA.muted, marginTop: 2 }}>{NOTIFS.filter(n => n.unread).length} sin leer</div>
          </div>
          <CloseBtn onClick={onClose}/>
        </div>
        <div style={{ padding: '0 16px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {NOTIFS.map(n => <NotifCard key={n.id} n={n} onSign={() => onSign(CONTRACTS.find(c => c.id === n.contractId))} onRequest={() => onRequest(CONTRACTS.find(c => c.id === n.contractId))}/>)}
        </div>
      </div>
    </>
  );
}

function NotifCard({ n, onSign, onRequest }) {
  const config = {
    new_contract: { icon: 'sparkle', color: FA.blue, bg: FA.skySoft },
    payment:      { icon: 'arrDown', color: FA.ok,   bg: '#dcfce7'  },
    reminder:     { icon: 'bell',    color: FA.warn,  bg: '#fef3c7' },
  }[n.type];
  return (
    <div style={{
      background: n.unread ? '#fff' : FA.bgSoft, borderRadius: 14, padding: 14,
      border: '1px solid ' + (n.unread ? 'rgba(37,99,235,0.15)' : FA.hairline),
      display: 'flex', gap: 12, position: 'relative',
    }}>
      {n.unread && <span style={{ position: 'absolute', top: 14, right: 14, width: 7, height: 7, borderRadius: 4, background: FA.blue }}/>}
      <div style={{ width: 36, height: 36, borderRadius: 10, background: config.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={config.icon} size={17} color={config.color} strokeWidth={2}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
          <span style={{ fontSize: 13.5, fontWeight: 650, color: FA.ink }}>{n.title}</span>
          <span style={{ fontSize: 10.5, color: FA.muted, flexShrink: 0, marginRight: n.unread ? 12 : 0 }}>{n.time}</span>
        </div>
        <div style={{ fontSize: 12.5, color: FA.inkSoft, marginTop: 4, lineHeight: 1.4 }}>{n.body}</div>
        {n.type === 'new_contract' && (
          <button onClick={onSign} style={{
            marginTop: 10, background: FA.blue, color: '#fff', border: 'none',
            padding: '7px 12px', borderRadius: 9, fontSize: 12, fontWeight: 600,
            cursor: 'pointer', fontFamily: FA.sans, display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>Ver y firmar <Icon name="arrUpRight" size={12} color="#fff" strokeWidth={2.2}/></button>
        )}
        {n.type === 'reminder' && n.contractId && (
          <button onClick={onRequest} style={{
            marginTop: 10, background: '#ea580c', color: '#fff', border: 'none',
            padding: '7px 12px', borderRadius: 9, fontSize: 12, fontWeight: 600,
            cursor: 'pointer', fontFamily: FA.sans, display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>Ver vencimiento <Icon name="arrUpRight" size={12} color="#fff" strokeWidth={2.2}/></button>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Contract Detail Sheet — overview + action selection
// ─────────────────────────────────────────────────────────────
function ContractDetailSheet({ contract, onClose, onSign, onRequest }) {
  if (!contract) return null;
  const c = contract;
  const retorno = Math.round(c.amount * c.rate / 100 * 0.5);
  const total = c.amount + retorno;
  const badgeKind = c.awaitingDecision ? 'decide' : c.status;
  const statusLabel = c.awaitingDecision ? 'Pendiente' : { active: 'Activo', pending: 'Pendiente', closed: 'Completado' }[c.status];
  const initials = c.counterparty.split(' ').map(w => w[0]).slice(0, 2).join('');
  const avatarColor = c.awaitingDecision ? '#ea580c' : { active: FA.blue, pending: '#d97706', closed: FA.muted }[c.status];

  return (
    <>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, zIndex: 60,
        background: 'rgba(10,22,40,0.55)', backdropFilter: 'blur(4px)',
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 70,
        background: '#fff', borderRadius: '24px 24px 0 0',
        fontFamily: FA.sans, overflow: 'hidden',
        animation: 'fa-slide-up .28s cubic-bezier(.2,.8,.3,1)',
        maxHeight: '90%', overflowY: 'auto',
      }}>
        <Pill/>
        {/* header */}
        <div style={{ padding: '8px 20px 20px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{
                width: 52, height: 52, borderRadius: 16, flexShrink: 0,
                background: avatarColor + '18',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 18, fontWeight: 700, color: avatarColor,
                border: `1.5px solid ${avatarColor}22`,
              }}>{initials}</div>
              <div>
                <div style={{ fontSize: 18, fontWeight: 700, color: FA.ink, letterSpacing: -0.4, lineHeight: 1.2 }}>
                  {c.counterparty}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
                  <span style={{ fontSize: 11, color: FA.muted, fontFamily: FA.mono, fontWeight: 600 }}>{c.id}</span>
                  <Badge kind={badgeKind}>{statusLabel}</Badge>
                </div>
              </div>
            </div>
            <CloseBtn onClick={onClose}/>
          </div>

          {/* key metrics */}
          <div style={{
            marginTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
          }}>
            <MetricBox label="Monto invertido"  value={fmtUSD(c.amount)}        mono/>
            <MetricBox label="Tasa anual"        value={`${c.rate.toFixed(1)}%`} color={FA.ok}/>
            <MetricBox label="Retorno estimado"  value={fmtUSD(retorno)}         color={FA.blue} mono/>
            <MetricBox label="Vencimiento"       value={fmtDateES(new Date(c.maturity)) + ' 2026'}/>
          </div>

          {/* progress — active only */}
          {c.status === 'active' && (
            <div style={{ marginTop: 18 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: FA.muted, marginBottom: 8 }}>
                <span>{c.progress < 50 ? 'Avanzando bien' : c.progress < 90 ? 'Casi en la meta' : 'Por vencer pronto'}</span>
                <span style={{ fontWeight: 600, color: FA.ink }}>{c.progress}%</span>
              </div>
              <div style={{ height: 6, background: FA.hairline, borderRadius: 3, overflow: 'hidden' }}>
                <div style={{
                  width: `${c.progress}%`, height: '100%',
                  background: 'linear-gradient(90deg, #38bdf8 0%, #2563eb 100%)',
                  borderRadius: 3, transition: 'width .4s',
                }}/>
              </div>
            </div>
          )}

          {/* total available banner — active only */}
          {c.status === 'active' && (
            <div style={{
              marginTop: 16, padding: '12px 16px', borderRadius: 12,
              background: 'linear-gradient(135deg, #eff8ff 0%, #dbeafe 100%)',
              border: '1px solid rgba(37,99,235,0.12)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div style={{ fontSize: 12, color: FA.inkSoft }}>Total al vencimiento</div>
              <div style={{ fontSize: 17, fontWeight: 700, color: FA.blue, fontFamily: FA.mono, letterSpacing: -0.3 }}>
                {fmtUSD(total)}
              </div>
            </div>
          )}

          {/* decision breakdown — withdraw + reinvestment */}
          {c.status === 'active' && c.decision && (
            <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div style={{
                padding: '12px 14px', borderRadius: 12,
                background: '#f0fdf4', border: '1px solid rgba(22,163,74,0.18)',
              }}>
                <div style={{ fontSize: 11, color: '#166534', fontWeight: 600, marginBottom: 4 }}>Por retirar</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: '#16a34a', fontFamily: FA.mono, letterSpacing: -0.3 }}>
                  {fmtUSD(c.decision.withdraw)}
                </div>
              </div>
              <div style={{
                padding: '12px 14px', borderRadius: 12,
                background: '#eff8ff', border: '1px solid rgba(37,99,235,0.15)',
              }}>
                <div style={{ fontSize: 11, color: '#1e40af', fontWeight: 600, marginBottom: 4 }}>Reinversión</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: FA.blue, fontFamily: FA.mono, letterSpacing: -0.3 }}>
                  {fmtUSD(total - c.decision.withdraw)}
                </div>
              </div>
            </div>
          )}

          {/* pending sign reminder */}
          {c.status === 'pending' && (
            <div style={{
              marginTop: 16, padding: '12px 16px', borderRadius: 12,
              background: '#fef3c7', border: '1px solid rgba(146,64,14,0.12)',
              display: 'flex', alignItems: 'center', gap: 10,
              fontSize: 12.5, color: '#92400e', fontWeight: 600,
            }}>
              <Icon name="pen" size={15} color="#92400e" strokeWidth={2}/>
              Este contrato está listo para tu firma digital
            </div>
          )}
        </div>

        {/* action buttons */}
        <div style={{ padding: '0 20px 32px', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {c.status === 'pending' && (
            <PrimaryBtn onClick={onSign} icon="pen">Firmar contrato</PrimaryBtn>
          )}
          {c.status === 'active' && !c.decision && (
            <>
              <PrimaryBtn onClick={onRequest} icon="download">Solicitar monto</PrimaryBtn>
              <SecondaryBtn onClick={onClose}>Cerrar</SecondaryBtn>
            </>
          )}
          {c.status === 'active' && c.decision && (
            <SecondaryBtn onClick={onClose}>Cerrar</SecondaryBtn>
          )}
          {c.status === 'closed' && (
            <SecondaryBtn onClick={onClose}>Cerrar</SecondaryBtn>
          )}
        </div>
      </div>
    </>
  );
}

function MetricBox({ label, value, color, mono }) {
  return (
    <div style={{
      padding: '12px 14px', background: FA.bgSoft, borderRadius: 12,
    }}>
      <div style={{ fontSize: 10.5, color: FA.muted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>
        {label}
      </div>
      <div style={{
        fontSize: 16, fontWeight: 700, marginTop: 4,
        color: color || FA.ink,
        fontFamily: mono ? FA.mono : FA.sans,
        letterSpacing: mono ? -0.3 : 0,
      }}>{value}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Request Amount Sheet — withdrawal + planned reinvestment split
// ─────────────────────────────────────────────────────────────
function RequestAmountSheet({ contract, onClose, onBack }) {
  if (!contract) return null;
  const c = contract;
  const retorno = Math.round(c.amount * c.rate / 100 * 0.5);
  const maxAmount = c.amount + retorno;
  const [rawValue, setRawValue] = React.useState('');
  const [reinvestAll, setReinvestAll] = React.useState(false);
  const [step, setStep] = React.useState('input'); // input | done
  const inputRef = React.useRef(null);

  const requested = reinvestAll ? 0 : Math.min(Math.max(0, parseInt(rawValue.replace(/[^0-9]/g, '')) || 0), maxAmount);
  const reinvested = maxAmount - requested;
  const canConfirm = reinvestAll || (requested > 0 && requested <= maxAmount);

  const setQuick = (pct) => {
    setReinvestAll(false);
    const val = pct === 1 ? maxAmount : Math.round(maxAmount * pct / 1000) * 1000;
    setRawValue(String(val));
  };

  const handleInput = (e) => {
    setReinvestAll(false);
    const digits = e.target.value.replace(/[^0-9]/g, '');
    setRawValue(digits);
  };

  if (step === 'done') {
    return (
      <>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'rgba(10,22,40,0.55)', backdropFilter: 'blur(4px)' }}/>
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 70,
          background: '#fff', borderRadius: '24px 24px 0 0',
          fontFamily: FA.sans, animation: 'fa-slide-up .28s cubic-bezier(.2,.8,.3,1)',
        }}>
          <Pill/>
          <div style={{ padding: '16px 22px 36px', textAlign: 'center' }}>
            <div style={{
              width: 72, height: 72, borderRadius: '50%', margin: '0 auto',
              background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="check" size={40} color={FA.ok} strokeWidth={2.4}/>
            </div>
            <div style={{ fontSize: 22, fontWeight: 700, color: FA.ink, marginTop: 16, letterSpacing: -0.5 }}>
              ¡Solicitud enviada!
            </div>
            <div style={{ fontSize: 13.5, color: FA.muted, marginTop: 8, lineHeight: 1.6 }}>
              Tu solicitud de retiro fue recibida.<br/>Se procesará al vencimiento del contrato.
            </div>

            {/* split summary receipt */}
            <div style={{ marginTop: 24, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <SplitCard
                kind="withdraw"
                label="A retirar"
                amount={requested}
                sub={`Se acreditará el ${fmtDateES(new Date(c.maturity))} 2026`}
              />
              {reinvested > 0 && (
                <SplitCard
                  kind="reinvest"
                  label="Inversión planificada"
                  amount={reinvested}
                  sub="Este valor será incluido en el siguiente contrato de inversión."
                />
              )}
            </div>

            <button onClick={onClose} style={{
              marginTop: 24, width: '100%', background: FA.blue, color: '#fff', border: 'none',
              padding: '15px', borderRadius: 14, fontSize: 14, fontWeight: 650,
              cursor: 'pointer', fontFamily: FA.sans,
              boxShadow: '0 6px 20px rgba(37,99,235,0.28)',
            }}>Ir a mis contratos</button>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'rgba(10,22,40,0.55)', backdropFilter: 'blur(4px)' }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 70,
        background: '#fff', borderRadius: '24px 24px 0 0',
        fontFamily: FA.sans, overflow: 'hidden',
        animation: 'fa-slide-up .28s cubic-bezier(.2,.8,.3,1)',
        maxHeight: '94%', overflowY: 'auto',
      }}>
        <Pill/>

        {/* mini header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 20px 16px' }}>
          <button onClick={onBack} style={{
            background: FA.bgSoft, border: 'none', width: 34, height: 34, borderRadius: 10,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <Icon name="back" size={16} color={FA.inkSoft} strokeWidth={2}/>
          </button>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700, color: FA.ink, letterSpacing: -0.3 }}>Solicitar monto</div>
            <div style={{ fontSize: 11.5, color: FA.muted, marginTop: 1 }}>{c.counterparty} · {c.id}</div>
          </div>
        </div>

        <div style={{ padding: '0 20px 32px' }}>
          {/* total available */}
          <div style={{
            padding: '14px 16px', borderRadius: 14,
            background: 'linear-gradient(135deg, #eff8ff 0%, #dbeafe 100%)',
            border: '1px solid rgba(37,99,235,0.12)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            marginBottom: 20,
          }}>
            <div>
              <div style={{ fontSize: 11, color: FA.inkSoft, fontWeight: 500 }}>Total disponible al vencimiento</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: FA.blue, fontFamily: FA.mono, letterSpacing: -0.5, marginTop: 2 }}>
                {fmtUSD(maxAmount)}
              </div>
            </div>
            <div style={{
              background: 'rgba(37,99,235,0.10)', borderRadius: 10,
              padding: '6px 10px', fontSize: 11, color: FA.blue, fontWeight: 600,
            }}>
              {fmtDateES(new Date(c.maturity))}
            </div>
          </div>

          {/* reinvest all option */}
          <button onClick={() => { setReinvestAll(true); setRawValue(''); }} style={{
            width: '100%', marginBottom: 14, padding: '13px 16px',
            borderRadius: 12, border: `1.5px solid ${reinvestAll ? FA.blue : FA.hairline}`,
            background: reinvestAll ? FA.skySoft : '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            cursor: 'pointer', fontFamily: FA.sans,
          }}>
            <div style={{ textAlign: 'left' }}>
              <div style={{ fontSize: 13, fontWeight: 650, color: reinvestAll ? FA.blue : FA.ink }}>Reinvertir todo</div>
              <div style={{ fontSize: 11, color: FA.muted, marginTop: 2 }}>No retirar nada · renovar el contrato</div>
            </div>
            <div style={{
              width: 20, height: 20, borderRadius: '50%',
              border: `2px solid ${reinvestAll ? FA.blue : FA.hairline}`,
              background: reinvestAll ? FA.blue : '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              {reinvestAll && <Icon name="check" size={11} color="#fff" strokeWidth={3}/>}
            </div>
          </button>

          {/* quick % buttons */}
          <div style={{ fontSize: 11.5, color: FA.muted, fontWeight: 600, marginBottom: 10 }}>
            O elige un monto a retirar
          </div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
            {[['25%', 0.25], ['50%', 0.5], ['75%', 0.75], ['Máximo', 1]].map(([label, pct]) => (
              <button key={label} onClick={() => setQuick(pct)} style={{
                flex: 1, border: '1.5px solid',
                borderColor: requested === Math.min(pct === 1 ? maxAmount : Math.round(maxAmount * pct / 1000) * 1000, maxAmount)
                  ? FA.blue : FA.hairline,
                background: requested === Math.min(pct === 1 ? maxAmount : Math.round(maxAmount * pct / 1000) * 1000, maxAmount)
                  ? FA.skySoft : '#fff',
                color: FA.ink, padding: '9px 4px', borderRadius: 10,
                fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: FA.sans,
              }}>{label}</button>
            ))}
          </div>

          {/* amount input */}
          <div style={{ fontSize: 11.5, color: FA.muted, fontWeight: 600, marginBottom: 8 }}>
            O escribe el monto exacto
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 0,
            border: `1.5px solid ${rawValue ? FA.blue : FA.hairline}`,
            borderRadius: 14, overflow: 'hidden', background: '#fff',
            transition: 'border-color .15s',
          }}>
            <div style={{
              padding: '16px 16px 16px 18px', fontSize: 22, fontWeight: 600,
              color: rawValue ? FA.ink : FA.muted, fontFamily: FA.mono,
              background: FA.bgSoft, borderRight: '1px solid ' + FA.hairline,
            }}>$</div>
            <input
              ref={inputRef}
              type="number"
              min="0"
              max={maxAmount}
              value={rawValue}
              onChange={handleInput}
              placeholder="0"
              style={{
                flex: 1, border: 'none', outline: 'none', padding: '16px 18px',
                fontSize: 22, fontWeight: 600, color: FA.ink, fontFamily: FA.mono,
                background: 'transparent', letterSpacing: -0.5,
                MozAppearance: 'textfield',
              }}
            />
          </div>
          {requested > maxAmount && (
            <div style={{ fontSize: 11.5, color: FA.danger, marginTop: 6, fontWeight: 600 }}>
              El monto supera el máximo disponible ({fmtUSD(maxAmount)})
            </div>
          )}

          {/* split visualization */}
          {(reinvestAll || requested > 0) && (
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <div style={{ fontSize: 11.5, color: FA.muted, fontWeight: 600 }}>Distribución de fondos</div>

              {/* visual bar */}
              <div style={{ height: 8, borderRadius: 4, overflow: 'hidden', background: FA.hairline, display: 'flex' }}>
                <div style={{
                  width: `${(requested / maxAmount) * 100}%`, height: '100%',
                  background: FA.ok, transition: 'width .25s',
                }}/>
                <div style={{
                  flex: 1, height: '100%',
                  background: 'linear-gradient(90deg, #38bdf8, #2563eb)', transition: 'width .25s',
                }}/>
              </div>

              <SplitCard
                kind="withdraw"
                label="A retirar"
                amount={requested}
                sub="Se acreditará a tu balance al vencimiento"
              />
              {reinvested > 0 && (
                <SplitCard
                  kind="reinvest"
                  label="Inversión planificada"
                  amount={reinvested}
                  sub="Este valor será incluido en el siguiente contrato de inversión."
                />
              )}
            </div>
          )}

          <button
            onClick={() => canConfirm && setStep('done')}
            style={{
              marginTop: 22, width: '100%', border: 'none',
              background: canConfirm
                ? 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)'
                : FA.hairline,
              color: canConfirm ? '#fff' : FA.muted,
              padding: '15px', borderRadius: 14, fontSize: 14, fontWeight: 650,
              cursor: canConfirm ? 'pointer' : 'default', fontFamily: FA.sans,
              boxShadow: canConfirm ? '0 6px 20px rgba(37,99,235,0.28)' : 'none',
              transition: 'background .2s, box-shadow .2s',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
            <Icon name="check" size={16} color={canConfirm ? '#fff' : FA.muted} strokeWidth={2.4}/>
            Confirmar solicitud
          </button>
          <button onClick={onClose} style={{
            marginTop: 8, width: '100%', background: 'transparent', color: FA.muted,
            border: 'none', padding: 12, fontSize: 13, fontWeight: 500, cursor: 'pointer',
          }}>Cancelar</button>
        </div>
      </div>
    </>
  );
}

// The split card — green for withdrawal, blue for reinvestment
function SplitCard({ kind, label, amount, sub }) {
  const isWithdraw = kind === 'withdraw';
  const accentColor = isWithdraw ? FA.ok : FA.blue;
  const bgColor = isWithdraw ? '#f0fdf4' : '#eff8ff';
  return (
    <div style={{
      borderRadius: 12, overflow: 'hidden',
      display: 'flex', background: bgColor,
      border: `1px solid ${accentColor}20`,
    }}>
      {/* left accent bar */}
      <div style={{ width: 4, flexShrink: 0, background: accentColor }}/>
      <div style={{ flex: 1, padding: '13px 14px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div style={{
            fontSize: 11.5, fontWeight: 600, color: accentColor,
            letterSpacing: 0.2, textTransform: 'uppercase',
          }}>{label}</div>
          <div style={{
            fontSize: 17, fontWeight: 700, color: accentColor,
            fontFamily: FA.mono, letterSpacing: -0.3,
          }}>{fmtUSD(amount)}</div>
        </div>
        <div style={{ fontSize: 11.5, color: FA.muted, marginTop: 5, lineHeight: 1.5 }}>{sub}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Signature Pad + Signing Sheet
// ─────────────────────────────────────────────────────────────
function SignaturePad({ onResult, onClear: onClearCb }) {
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);
  const lastPt = React.useRef(null);
  const [isEmpty, setIsEmpty] = React.useState(true);
  const CANVAS_W = 354, CANVAS_H = 150;

  const getCtx = () => {
    const c = canvasRef.current;
    if (!c) return null;
    const ctx = c.getContext('2d');
    ctx.lineJoin = 'round'; ctx.lineCap = 'round';
    ctx.strokeStyle = FA.ink; ctx.lineWidth = 2.2;
    return ctx;
  };
  const ptFrom = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const src = e.touches ? e.touches[0] : e;
    return { x: (src.clientX - rect.left) * (CANVAS_W / rect.width), y: (src.clientY - rect.top) * (CANVAS_H / rect.height) };
  };
  const startDraw = (e) => {
    e.preventDefault(); drawing.current = true; lastPt.current = ptFrom(e);
    setIsEmpty(false);
    const ctx = getCtx();
    if (ctx) { ctx.beginPath(); ctx.moveTo(lastPt.current.x, lastPt.current.y); }
  };
  const draw = (e) => {
    e.preventDefault(); if (!drawing.current) return;
    const pt = ptFrom(e); const ctx = getCtx(); if (!ctx || !lastPt.current) return;
    const mid = { x: (lastPt.current.x + pt.x) / 2, y: (lastPt.current.y + pt.y) / 2 };
    ctx.quadraticCurveTo(lastPt.current.x, lastPt.current.y, mid.x, mid.y);
    ctx.stroke(); ctx.beginPath(); ctx.moveTo(mid.x, mid.y); lastPt.current = pt;
  };
  const endDraw = (e) => {
    if (!drawing.current) return; e.preventDefault(); drawing.current = false; lastPt.current = null;
    const ctx = getCtx(); if (ctx) ctx.closePath();
    if (onResult) onResult(canvasRef.current.toDataURL());
  };
  const clearPad = () => {
    const c = canvasRef.current; if (!c) return;
    c.getContext('2d').clearRect(0, 0, CANVAS_W, CANVAS_H);
    setIsEmpty(true); if (onResult) onResult(null); if (onClearCb) onClearCb();
  };

  return (
    <div style={{ position: 'relative', userSelect: 'none' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{ fontSize: 11.5, color: FA.muted, fontWeight: 600, letterSpacing: 0.3 }}>FIRMA AQUÍ</span>
        <button onClick={clearPad} disabled={isEmpty} style={{
          background: 'none', border: 'none', cursor: isEmpty ? 'default' : 'pointer',
          fontSize: 12, fontWeight: 600, color: isEmpty ? FA.hairline : FA.blue,
          fontFamily: FA.sans, padding: '2px 0',
          display: 'flex', alignItems: 'center', gap: 5, transition: 'color .15s',
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>
          </svg>
          Borrar
        </button>
      </div>
      <div style={{
        position: 'relative', borderRadius: 14, background: '#fafbfc',
        border: `1.5px solid ${isEmpty ? FA.hairline : FA.blue + '55'}`,
        overflow: 'hidden', transition: 'border-color .2s',
      }}>
        <div style={{ position: 'absolute', bottom: 36, left: 20, right: 20, height: 1, background: 'rgba(148,163,184,0.3)', pointerEvents: 'none' }}/>
        <div style={{ position: 'absolute', bottom: 40, left: 20, fontSize: 18, color: 'rgba(148,163,184,0.5)', fontWeight: 400, pointerEvents: 'none', lineHeight: 1 }}>×</div>
        {isEmpty && (
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none', fontSize: 13, color: 'rgba(148,163,184,0.6)', fontStyle: 'italic' }}>
            Dibuja tu firma con el dedo
          </div>
        )}
        <canvas ref={canvasRef} width={CANVAS_W} height={CANVAS_H}
          style={{ display: 'block', width: '100%', height: CANVAS_H, cursor: 'crosshair', touchAction: 'none' }}
          onPointerDown={startDraw} onPointerMove={draw} onPointerUp={endDraw} onPointerLeave={endDraw}
          onTouchStart={startDraw} onTouchMove={draw} onTouchEnd={endDraw}/>
      </div>
      {!isEmpty && (
        <div style={{ marginTop: 8, fontSize: 11, color: FA.ok, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5 }}>
          <Icon name="check" size={12} color={FA.ok} strokeWidth={2.5}/>Firma capturada
        </div>
      )}
    </div>
  );
}

function SignContractSheet({ contract, onClose, onBack }) {
  const [step, setStep] = React.useState('sign'); // sign | confirming | done
  const [sigDataUrl, setSigDataUrl] = React.useState(null);
  if (!contract) return null;
  const canSign = sigDataUrl !== null;

  React.useEffect(() => {
    if (step === 'confirming') { const t = setTimeout(() => setStep('done'), 1400); return () => clearTimeout(t); }
  }, [step]);

  return (
    <>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 60, background: 'rgba(10,22,40,0.55)', backdropFilter: 'blur(4px)' }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, zIndex: 70,
        background: '#fff', borderRadius: '24px 24px 0 0', fontFamily: FA.sans,
        animation: 'fa-slide-up .28s cubic-bezier(.2,.8,.3,1)',
        maxHeight: '92%', overflowY: 'auto',
      }}>
        <Pill/>
        {step === 'sign' && (
          <div style={{ padding: '8px 22px 28px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
              <button onClick={onBack} style={{ background: FA.bgSoft, border: 'none', width: 34, height: 34, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                <Icon name="back" size={16} color={FA.inkSoft} strokeWidth={2}/>
              </button>
              <div>
                <div style={{ fontSize: 17, fontWeight: 700, color: FA.ink, letterSpacing: -0.3 }}>Firma digital</div>
                <div style={{ fontSize: 11.5, color: FA.muted, marginTop: 1 }}>{contract.counterparty} · {contract.id}</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, padding: '12px 14px', borderRadius: 12, background: FA.bgSoft, marginBottom: 20, alignItems: 'flex-start' }}>
              <Icon name="pen" size={16} color={FA.blue} strokeWidth={2}/>
              <div style={{ fontSize: 12.5, color: FA.inkSoft, lineHeight: 1.5 }}>
                Dibuja tu firma en el recuadro de abajo. Usa el dedo o el cursor para trazar tu rúbrica habitual.
              </div>
            </div>
            <SignaturePad onResult={setSigDataUrl} onClear={() => setSigDataUrl(null)}/>
            <div style={{ marginTop: 18, padding: '10px 14px', borderRadius: 10, background: '#f8fafc', border: '1px solid ' + FA.hairline, fontSize: 11, color: FA.muted, lineHeight: 1.6, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
              <Icon name="shield" size={14} color={FA.muted} strokeWidth={1.8}/>
              <span>Tu firma tiene validez legal bajo la Ley 19.799 de Firma Electrónica. Fecha y hora quedarán registradas en el contrato.</span>
            </div>
            <button onClick={() => canSign && setStep('confirming')} style={{
              marginTop: 18, width: '100%', border: 'none',
              background: canSign ? 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)' : FA.hairline,
              color: canSign ? '#fff' : FA.muted, padding: '15px', borderRadius: 14,
              fontSize: 14, fontWeight: 650, cursor: canSign ? 'pointer' : 'default',
              fontFamily: FA.sans, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: canSign ? '0 6px 20px rgba(37,99,235,0.30)' : 'none', transition: 'background .2s, box-shadow .2s',
            }}>
              <Icon name="check" size={16} color={canSign ? '#fff' : FA.muted} strokeWidth={2.4}/>
              Confirmar firma
            </button>
            <button onClick={onClose} style={{ marginTop: 8, width: '100%', background: 'transparent', color: FA.muted, border: 'none', padding: 12, fontSize: 13, fontWeight: 500, cursor: 'pointer' }}>Cancelar</button>
          </div>
        )}
        {step === 'confirming' && (
          <div style={{ padding: '52px 22px 72px', textAlign: 'center' }}>
            <div style={{ width: 72, height: 72, borderRadius: '50%', margin: '0 auto', background: FA.skySoft, position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="72" height="72" viewBox="0 0 72 72" style={{ position: 'absolute', inset: 0, animation: 'fa-spin 1s linear infinite' }}>
                <circle cx="36" cy="36" r="32" fill="none" stroke={FA.blue} strokeWidth="3" strokeOpacity="0.2"/>
                <circle cx="36" cy="36" r="32" fill="none" stroke={FA.blue} strokeWidth="3" strokeDasharray="50 150" strokeLinecap="round"/>
              </svg>
              <Icon name="pen" size={26} color={FA.blue} strokeWidth={1.8}/>
            </div>
            <div style={{ fontSize: 16, fontWeight: 650, color: FA.ink, marginTop: 22 }}>Registrando firma…</div>
            <div style={{ fontSize: 12.5, color: FA.muted, marginTop: 6 }}>Guardando con marca de tiempo segura</div>
          </div>
        )}
        {step === 'done' && (
          <div style={{ padding: '32px 22px 32px' }}>
            <div style={{ textAlign: 'center', marginBottom: 26 }}>
              <div style={{ width: 72, height: 72, borderRadius: '50%', margin: '0 auto', background: '#dcfce7', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="check" size={40} color={FA.ok} strokeWidth={2.4}/>
              </div>
              <div style={{ fontSize: 20, fontWeight: 700, color: FA.ink, marginTop: 16, letterSpacing: -0.4 }}>¡Contrato firmado!</div>
              <div style={{ fontSize: 13, color: FA.muted, marginTop: 6, lineHeight: 1.5 }}>{fmtUSD(contract.amount)} se reflejará<br/>en tu portafolio en unos minutos.</div>
            </div>
            <div style={{ borderRadius: 16, border: '1px solid ' + FA.hairline, overflow: 'hidden', marginBottom: 20 }}>
              <div style={{ padding: '12px 16px', background: FA.bgSoft, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5, color: FA.muted, fontWeight: 600 }}>
                <span>Tu firma</span>
                <span style={{ fontFamily: FA.mono, color: FA.ink }}>{new Date().toLocaleDateString('es', { day: '2-digit', month: 'short', year: 'numeric' })}</span>
              </div>
              {sigDataUrl ? (
                <div style={{ background: '#fff', padding: '10px 16px', minHeight: 80, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <img src={sigDataUrl} alt="Firma" style={{ maxWidth: '100%', maxHeight: 80, objectFit: 'contain' }}/>
                </div>
              ) : <div style={{ height: 80, background: '#fff' }}/>}
              <div style={{ padding: '10px 16px', background: FA.bgSoft, borderTop: '1px solid ' + FA.hairline, display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: FA.muted }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><Icon name="shield" size={12} color={FA.ok} strokeWidth={2}/>Verificado · Factor Activo</span>
                <span style={{ fontFamily: FA.mono }}>{contract.id}</span>
              </div>
            </div>
            <button onClick={onClose} style={{ width: '100%', background: FA.blue, color: '#fff', border: 'none', padding: '15px', borderRadius: 14, fontSize: 14, fontWeight: 650, cursor: 'pointer', fontFamily: FA.sans, boxShadow: '0 6px 20px rgba(37,99,235,0.28)' }}>Ir a mis contratos</button>
          </div>
        )}
      </div>
      <style>{`@keyframes fa-spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}`}</style>
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Shared micro-components
// ─────────────────────────────────────────────────────────────
const Pill = () => (
  <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
    <div style={{ width: 40, height: 4, borderRadius: 2, background: FA.hairline }}/>
  </div>
);

const CloseBtn = ({ onClick }) => (
  <button onClick={onClick} style={{
    background: FA.bgSoft, border: 'none', width: 32, height: 32, borderRadius: 10,
    display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
  }}>
    <Icon name="close" size={16} color={FA.inkSoft} strokeWidth={2}/>
  </button>
);

const PrimaryBtn = ({ onClick, icon, children }) => (
  <button onClick={onClick} style={{
    width: '100%', background: 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%)', color: '#fff',
    border: 'none', padding: '15px', borderRadius: 14, fontSize: 14, fontWeight: 650,
    cursor: 'pointer', fontFamily: FA.sans, display: 'flex', alignItems: 'center',
    justifyContent: 'center', gap: 8, boxShadow: '0 6px 20px rgba(37,99,235,0.25)',
  }}>
    {icon && <Icon name={icon} size={16} color="#fff" strokeWidth={2.2}/>}
    {children}
  </button>
);

const SecondaryBtn = ({ onClick, children }) => (
  <button onClick={onClick} style={{
    width: '100%', background: FA.bgSoft, color: FA.muted, border: 'none',
    padding: '13px', borderRadius: 14, fontSize: 13, fontWeight: 500,
    cursor: 'pointer', fontFamily: FA.sans,
  }}>{children}</button>
);

function KV({ k, v, color }) {
  return (
    <div>
      <div style={{ fontSize: 10.5, color: FA.muted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>{k}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: color || FA.ink, marginTop: 3, fontFamily: FA.mono, letterSpacing: -0.3 }}>{v}</div>
    </div>
  );
}

Object.assign(window, { NotificationsSheet, ContractDetailSheet, SignContractSheet, RequestAmountSheet });
