# react-native-snapmint3

A React Native package that provides Snapmint payment integration with EMI widget components and native checkout functionality. Features enhanced callback-based API with comprehensive error handling and debugging support.

## 🚀 Features

- **Enhanced Payment Integration**: Native checkout with dynamic URL support and callback-based API
- **Comprehensive Error Handling**: Detailed error reporting with timeout protection
- **EMI Widget Component**: Interactive EMI calculator with custom styling
- **Dynamic API Integration**: Fetch EMI data from Snapmint merchant API
- **Custom Font Support**: Full font family and size customization
- **TypeScript Support**: Complete TypeScript definitions included
- **Advanced Debugging**: Detailed logging and event emitter validation
- **Promise & Callback Support**: Flexible API supporting both Promise and callback patterns

## 📦 Installation

Install the package and required peer dependency:

```sh
# Using npm
npm install react-native-snapmint3 react-native-webview --save

# Or using yarn
yarn add react-native-snapmint3 react-native-webview
```

### iOS (CocoaPods)

```sh
cd ios
pod install --clean-install
cd ..
```

Notes:
- React Native (>= 0.60) supports autolinking. No manual Android linking is required.
- If you face build cache issues, clean derived data and reinstall pods.
  - `rm -rf ~/Library/Developer/Xcode/DerivedData`
  - `cd ios && pod deintegrate && pod install --clean-install`

Requirements:
- iOS 15.0+ (SnapmintMerchantSdk 1.0.12)

## 💳 Payment Integration

### RNSnapmint3

The main checkout functionality for Snapmint payments with enhanced callback-based API.

#### Enhanced Callback API (Recommended)

```javascript
import RNSnapmint3 from 'react-native-snapmint3';

// Enhanced callback-based payment with comprehensive error handling
const handlePayment = () => {
  const checkoutUrl = "https://pay.sandbox.snapmint.com?id=53029&token=R_hR-rJMEWo_T4naTy7x&merchantId=1456&logo=null&title=null";
  
  RNSnapmint3.openSnapmintMerchant(checkoutUrl, {
    // Optional iOS-only header customization
    header: {
      enableHeader: true,
      showTitle: true,
      title: 'Checkout',
      backButtonColor: '#000000',
      titleColor: '#000000',
      headerColor: '#FFFFFF',
    },
    onSuccess: (result) => {
      console.log('✅ Payment successful:', result);
      console.log('Status:', result.status);
      console.log('Message:', result.responseMsg);
      console.log('Payment ID:', result.paymentId);
      console.log('Timestamp:', result.timestamp);
      
      // Handle successful payment
      Alert.alert('🎉 Payment Successful!', result.responseMsg);
    },
    onError: (error) => {
      console.error('❌ Payment failed:', error);
      console.error('Error Status:', error.status);
      console.error('Error Code:', error.statusCode);
      console.error('Error Message:', error.message);
      
      // Handle payment error
      Alert.alert('❌ Payment Failed', error.responseMsg || error.message);
    }
  });
};
```

#### Promise-based API (Legacy Support)

```javascript
// Promise-based approach (still supported)
const handlePaymentWithPromise = async () => {
  try {
    const checkoutUrl = "https://pay.sandbox.snapmint.com?id=53029&token=R_hR-rJMEWo_T4naTy7x&merchantId=1456&logo=null&title=null";
    
    const result = await RNSnapmint3.openSnapmintMerchant(checkoutUrl);
    
    if (result.status === 'success') {
      console.log('Payment successful:', result.message);
    } else {
      console.log('Payment failed:', result.message);
    }
  } catch (error) {
    console.error('Payment error:', error);
  }
};
```

#### RNSnapmint3 Methods

| Method | Parameters | Returns | Description |
|--------|------------|---------|-------------|
| `openSnapmintMerchant` | `checkoutUrl: string, options?: PaymentOptions` | `Promise<PaymentResult>` | Opens Snapmint payment checkout with enhanced error handling |

#### PaymentOptions Interface

```typescript
interface PaymentOptions {
  onSuccess?: (result: PaymentResult) => void;  // Success callback
  onError?: (error: PaymentError) => void;      // Error callback
  // iOS-only header customization
  header?: {
    enableHeader?: boolean;
    showTitle?: boolean;
    title?: string;
    backButtonColor?: string; // #RRGGBB or #AARRGGBB
    titleColor?: string;      // #RRGGBB or #AARRGGBB
    headerColor?: string;     // #RRGGBB or #AARRGGBB
  };
}
```

#### PaymentResult Interface

```typescript
interface PaymentResult {
  status: string;        // 'success' | 'failure'
  statusCode: number;    // HTTP status code (200 for success)
  message: string;       // Human readable message
  responseMsg: string;   // Response message
  paymentId?: string;    // Payment ID (if available)
  timestamp: string;     // ISO timestamp of the result
}
```

#### PaymentError Interface

```typescript
interface PaymentError {
  status: string;        // 'failure'
  statusCode: number;    // HTTP status code (300, 400, 408, etc.)
  message: string;       // Human readable error message
  responseMsg: string;   // Response error message
  timestamp: string;     // ISO timestamp of the error
}
```

## 🎨 EMI Widget Component

### SnapmintEMIWidget

Interactive EMI widget component that fetches data from Snapmint API and displays EMI options.

```javascript
import { SnapmintEMIWidget } from 'react-native-snapmint3';

<SnapmintEMIWidget
  amount={'999'}
  merchantPath={'7078/woodland-updated.json'}
  fontFamily={{ fontFamily: 'Inter-Regular', fontMultiplier: 4.5 }}
  disablePopup={false}
/>
```

#### SnapmintEMIWidget Props

| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| `amount` | `string` | ✅ | - | Order amount for EMI calculation |
| `merchantPath` | `string` | ❌ | - | Merchant config path (e.g., "1616/snap_ketch.json") - **NEW** |
| `jsonUrl` | `string` | ❌ | - | Full URL for merchant config (deprecated, use merchantPath) |
| `fontFamily` | `object` | ❌ | `{fontFamily: 'Inter-Regular', fontMultiplier: 15}` | Font configuration |
| `buttonWidth` | `number` | ❌ | `90% of screen width` | Custom button width |
| `disablePopup` | `boolean` | ❌ | `false` | Disable EMI popup modal |

> Reference implementation: see `TestProject/App.tsx` for real usage wiring of `SnapmintEMIWidget` and the checkout callbacks.

#### FontFamily Object

```typescript
interface FontFamily {
  fontFamily: string;    // Font family name
  fontMultiplier: number; // Font size multiplier
}
```

#### Ref Methods

The component exposes several methods via ref:

```javascript
const buttonRef = useRef();

// Available methods
buttonRef.current.showSnapmintEmiInfo(orderValue, merchantLink);
buttonRef.current.openModal();
buttonRef.current.closeModal();
buttonRef.current.getEmiData();
buttonRef.current.getCalculatedAmounts();
buttonRef.current.isLoading();
```

## 🔧 API Integration

### Merchant Path Structure

The component uses the Snapmint merchant API with the following structure:

- **Base URL**: `https://merchant-js.snapmint.com/`
- **Endpoint**: `assets/merchant/{merchantPath}`
- **Full URL**: `https://merchant-js.snapmint.com/assets/merchant/{merchantPath}`

### Example Merchant Paths

```javascript
// Standard merchant
merchantPath="1616/snap_ketch.json"

// Titan merchant
merchantPath="4858/snap_titan.json"

// Custom merchant
merchantPath="your-merchant-id/your-config.json"
```


## 🚀 Enhanced Features

### Advanced Error Handling

- **Comprehensive Error Reporting**: Detailed error information with status codes and messages
- **Timeout Protection**: 5-minute timeout to prevent hanging payment sessions
- **Automatic Cleanup**: Event listeners and resources are automatically cleaned up
- **Bridge Testing**: Native module bridge connection is validated before payment

### Debugging Support

- **Detailed Logging**: Comprehensive console logging with emoji indicators
- **Event Emitter Validation**: Event emitter setup is validated and tested
- **Bridge Connection Testing**: Native module bridge is tested before payment initiation
- **Manual Event Testing**: Support for manual event emission for debugging

### API Flexibility

- **Dual API Support**: Both Promise-based and callback-based APIs
- **Enhanced Callbacks**: Rich callback functions with detailed result/error objects
- **TypeScript Support**: Complete type definitions for all interfaces
- **Backward Compatibility**: Legacy Promise API still supported

## 🔄 Migration Guide (v1.x → v2.0)

### Breaking Changes

1. **Renamed Main Class**: `IndusBitCheckout` → `RNSnapmintCheckout`
2. **Removed Component**: `RNSnapmintButtonGold` has been removed
3. **New Required Parameter**: `openSnapmintMerchant()` now requires `checkoutUrl` parameter
4. **Package renamed**: `indusbit-math` → `react-native-snapmint3`

### Migration Steps

#### Before (v1.x)
```javascript
// Old usage
import IndusBitCheckout from 'indusbit-math';
await IndusBitCheckout.openSnapmintMerchant();
```

#### After (v2.0)
```javascript
import RNSnapmint3 from 'react-native-snapmint3';

// Enhanced Payment with callbacks
RNSnapmint3.openSnapmintMerchant(checkoutUrl, {
  onSuccess: (result) => console.log('Success:', result),
  onError: (error) => console.error('Error:', error)
});

## 🔧 TypeScript Support

The package includes complete TypeScript definitions:

```typescript
import RNSnapmint3, { 
  SnapmintEMIWidget, 
  PaymentResult,
  PaymentError,
  PaymentOptions,
  SnapmintEMIWidgetProps 
} from 'react-native-snapmint3';
```

## 📋 Requirements

- React Native >= 0.66.0
- React >= 16.8.0
- react-native-webview >= 11.26.0
- react-native-render-html >= 6.3.0

## 🔍 Debugging

### Console Logging

The package provides comprehensive console logging with emoji indicators:

- 🏁 App lifecycle events
- 📦 Module loading and availability
- 🚀 Payment flow initiation
- ✅ Success events
- ❌ Error events
- 🧪 Debug and testing events
- ⏰ Timeout events
- 🧹 Cleanup events

### Event Emitter Testing

The package automatically tests the event emitter setup and provides debugging information for troubleshooting.

## 📄 License

MIT

## 🤝 Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.

## 📞 Support

For support and questions, please open an issue on GitHub or contact the development team.

## 📈 Changelog

### v2.0.0
- ✨ Enhanced callback-based API with comprehensive error handling
- 🔧 Improved timeout protection (5-minute timeout)
- 🐛 Better error reporting with detailed status codes
- 🧪 Enhanced debugging support with detailed logging
- 🔄 Automatic cleanup of event listeners and resources
- 🧪 Native module bridge testing and validation
- 📝 Complete TypeScript definitions
- 🎨 Improved UI components and styling
- 🔄 Backward compatibility with Promise-based API
