# MessageBox

A global modal dialog system for displaying informational messages, confirmations, and user interactions with customizable buttons and styling.

## Features

- **Global Access**: Available throughout the application via `window.MessageBox`
- **Multiple Types**: Support for info, warning, and custom message types
- **Confirmation Dialogs**: Built-in confirm/cancel functionality
- **Draggable**: Users can drag the message box around the screen
- **Custom Buttons**: Configure custom button sets with different actions
- **HTML Content**: Support for both plain text and HTML content
- **Promise-based**: Returns promises for easy async handling
- **Auto-positioning**: Automatically centers on screen with drag support
- **Internationalization**: Built-in i18n support for button labels

## Installation

```bash
npm install @ticatec/uniface-element
```

## Setup

First, add the MessageBoxBoard to your root layout or app component:

```svelte
<script>
  import MessageBoxBoard from '@ticatec/uniface-element/MessageBox';
</script>

<!-- Your app content -->
<main>
  <!-- Your components -->
</main>

<!-- MessageBox Board - Global instance -->
<MessageBoxBoard appTitle="My Application" />
```

## Basic Usage

Once the MessageBoxBoard is mounted, you can use the global MessageBox instance:

```javascript
// Show an information message
await window.MessageBox.showInfo('Operation completed successfully!', 'Success');

// Show a confirmation dialog
const result = await window.MessageBox.showConfirm(
  'Are you sure you want to delete this item?', 
  'Confirm Delete'
);

if (result === ModalResult.MR_OK) {
  // User confirmed
  console.log('User confirmed the action');
} else {
  // User cancelled
  console.log('User cancelled the action');
}
```

## API Reference

### MessageBoxBoard Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `appTitle` | `string` | `null` | Default title for message boxes when no title is provided |

### Global Methods

#### `window.MessageBox.showInfo(message, title?, escapeHTML?)`

Shows an informational message with a close button.

**Parameters:**
- `message` (string): The message to display
- `title` (string, optional): Dialog title
- `escapeHTML` (boolean, optional): Whether to escape HTML content (default: true)

**Returns:** `Promise<void>`

#### `window.MessageBox.showConfirm(message, title?, escapeHTML?, type?)`

Shows a confirmation dialog with OK/Cancel buttons.

**Parameters:**
- `message` (string): The message to display
- `title` (string, optional): Dialog title
- `escapeHTML` (boolean, optional): Whether to escape HTML content (default: true)
- `type` ('info' | 'warning', optional): Icon type to display (default: 'info')

**Returns:** `Promise<ModalResult>`

### ModalResult Enum

```typescript
enum ModalResult {
  MR_OK = 1,      // User clicked OK/Confirm
  MR_CANCEL = 2,  // User clicked Cancel
  MR_CLOSE = 3    // User clicked Close/X button
}
```

## Examples

### Basic Information Message

```javascript
// Simple info message
await window.MessageBox.showInfo('Your changes have been saved successfully.');

// Info message with custom title
await window.MessageBox.showInfo(
  'The operation completed without any errors.',
  'Operation Complete'
);
```

### Confirmation Dialogs

```javascript
// Basic confirmation
const result = await window.MessageBox.showConfirm(
  'Do you want to save your changes before closing?',
  'Unsaved Changes'
);

if (result === ModalResult.MR_OK) {
  // Save changes
  saveChanges();
}

// Warning confirmation
const result = await window.MessageBox.showConfirm(
  'This action cannot be undone. Continue?',
  'Permanent Action',
  false,
  'warning'
);
```

### HTML Content

```javascript
// Display HTML content (escapeHTML = false)
await window.MessageBox.showInfo(
  '<strong>Important:</strong> Please check your <em>email</em> for verification.',
  'Email Verification',
  false
);

// Safe HTML escaping (default behavior)
await window.MessageBox.showInfo(
  'User input: <script>alert("xss")</script>', // Will be escaped
  'User Data'
);
```

### Error Handling

```javascript
try {
  const result = await window.MessageBox.showConfirm(
    'Delete all selected items?',
    'Bulk Delete'
  );
  
  if (result === ModalResult.MR_OK) {
    await deleteItems();
    await window.MessageBox.showInfo('Items deleted successfully.', 'Success');
  }
} catch (error) {
  await window.MessageBox.showInfo(
    'An error occurred. Please try again.',
    'Error',
    false,
    'warning'
  );
}
```

### Form Validation Example

```svelte
<script>
  import { ModalResult } from '@ticatec/uniface-element/MessageBox';
  
  async function handleSubmit() {
    if (!formData.name) {
      await window.MessageBox.showInfo(
        'Please enter your name before submitting.',
        'Required Field'
      );
      return;
    }
    
    const result = await window.MessageBox.showConfirm(
      'Submit the form with the provided information?',
      'Confirm Submission'
    );
    
    if (result === ModalResult.MR_OK) {
      try {
        await submitForm(formData);
        await window.MessageBox.showInfo(
          'Form submitted successfully!',
          'Success'
        );
      } catch (error) {
        await window.MessageBox.showInfo(
          'Failed to submit form. Please try again.',
          'Submission Error',
          false,
          'warning'
        );
      }
    }
  }
</script>
```

### Async Operations

```javascript
async function performAsyncOperation() {
  // Show loading state (could be implemented with a custom dialog)
  const confirmed = await window.MessageBox.showConfirm(
    'This operation may take several minutes. Continue?',
    'Long Running Operation'
  );
  
  if (confirmed === ModalResult.MR_OK) {
    try {
      await longRunningTask();
      await window.MessageBox.showInfo(
        'Operation completed successfully!',
        'Success'
      );
    } catch (error) {
      await window.MessageBox.showInfo(
        `Operation failed: ${error.message}`,
        'Error',
        false,
        'warning'
      );
    }
  }
}
```

### Dialog Chain Example

```javascript
async function handleDataLoss() {
  const saveFirst = await window.MessageBox.showConfirm(
    'You have unsaved changes. Would you like to save them first?',
    'Unsaved Changes'
  );
  
  if (saveFirst === ModalResult.MR_OK) {
    try {
      await saveData();
      await window.MessageBox.showInfo('Data saved successfully.', 'Saved');
    } catch (error) {
      const retry = await window.MessageBox.showConfirm(
        'Failed to save data. Try again?',
        'Save Error',
        false,
        'warning'
      );
      
      if (retry === ModalResult.MR_OK) {
        return handleDataLoss(); // Recursive retry
      }
    }
  }
  
  // Proceed with the original action
  proceedWithAction();
}
```

### Multiple MessageBox Prevention

```javascript
let messageBoxActive = false;

async function safeShowMessage(message, title) {
  if (messageBoxActive) {
    console.warn('MessageBox already active');
    return;
  }
  
  messageBoxActive = true;
  try {
    await window.MessageBox.showInfo(message, title);
  } finally {
    messageBoxActive = false;
  }
}
```

## Styling

The MessageBox uses CSS classes that can be customized:

```css
.uniface-message-board {
  /* Overlay background */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
}

.uniface-message-box {
  /* Dialog container */
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.title-bar {
  /* Draggable title area */
  cursor: move;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.box-content {
  /* Message content area */
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.control-bar {
  /* Button area */
  padding: 16px 20px;
  text-align: right;
  border-top: 1px solid #eee;
}
```

## Best Practices

1. **Use Meaningful Titles**: Provide clear, descriptive titles for better UX
2. **Keep Messages Concise**: Short, clear messages are more effective
3. **Handle Promises Properly**: Always await MessageBox calls or handle rejections
4. **Consider User Context**: Use appropriate message types (info vs warning)
5. **Avoid Message Spam**: Prevent multiple MessageBoxes from showing simultaneously
6. **Test HTML Content**: When using HTML, ensure content is safe and properly formatted
7. **Provide Context**: Include relevant information to help users make decisions

## TypeScript Support

The MessageBox includes full TypeScript definitions:

```typescript
import { ModalResult, type IMessageBox } from '@ticatec/uniface-element/MessageBox';

declare global {
  interface Window {
    MessageBox: IMessageBox;
  }
}

// Usage with type safety
const result: ModalResult = await window.MessageBox.showConfirm(
  'Delete this item?',
  'Confirm Delete'
);
```

## Accessibility

- Proper ARIA labels and roles
- Keyboard navigation support (ESC to close)
- Focus management
- Screen reader compatibility
- High contrast mode support

## Related Components

- [Dialog](../dialog/README.md) - For custom modal dialogs
- [Toast](../toast/README.md) - For non-blocking notifications
- [Button](../button/README.md) - For dialog actions