# Form Builder JSON Structure Documentation

## Overview
This document describes the complete JSON structure used by the Form Builder system for importing and exporting forms. The structure supports the full range of form components, scripts, styling, and metadata.

## Complete Form Structure

### Root Object
```json
{
  "formName": "string",           // Form name (required)
  "formDescription": "string",    // Form description (optional)
  "formId": "string",            // Form UUID (auto-generated when null)
  "components": [],              // Array of form components (required)
  "customScript": "string",      // Custom JavaScript code (optional)
  "customCSS": "string",         // Custom CSS styles (optional)
  "formEvents": {},              // Event configuration (optional)
  "scriptMode": "string"         // Script execution mode (optional)
}
```

### Form Events Configuration
```json
{
  "formEvents": {
    "onLoad": true,          // Execute script when form loads
    "onFieldChange": true,   // Execute script when fields change
    "onSubmit": false,       // Execute script before form submission
    "onValidation": false    // Execute script during field validation
  }
}
```

### Script Mode Options
- `"safe"` (default): Scripts run in secure sandbox with form functions only
- `"advanced"`: Broader JavaScript access with security restrictions

## Form Components Array

Each component in the `components` array follows this structure:

### Basic Component Structure
```json
{
  "id": "string",      // Auto-generated unique ID
  "type": "string",    // Component type (required)
  "props": {}          // Component properties (required)
}
```

### Component Types and Props

#### 1. Text Input Components

##### Text Field
```json
{
  "type": "text",
  "props": {
    "name": "field_name",              // Field name (required)
    "label": "Field Label",            // Display label (required)
    "placeholder": "Enter text...",    // Placeholder text
    "help": "Help text",               // Help description
    "validation": "required|min:3",    // Validation rules
    "value": "",                       // Default value
    "readonly": false,                 // Read-only state
    "width": "100%",                   // Field width
    "gridColumn": "span 12",           // Grid column span
    "conditionalLogic": {              // Conditional display logic
      "action": "show",                // show/hide/enable/disable
      "enabled": false,                // Enable conditional logic
      "operator": "and",               // and/or for multiple conditions
      "conditions": []                 // Array of conditions
    }
  }
}
```

##### Textarea
```json
{
  "type": "textarea",
  "props": {
    "name": "description",
    "label": "Description",
    "placeholder": "Enter description...",
    "help": "Detailed description",
    "validation": "required|min:10",
    "value": "",
    "rows": 4,
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Number Field
```json
{
  "type": "number",
  "props": {
    "name": "amount",
    "label": "Amount",
    "placeholder": "0.00",
    "help": "Enter amount",
    "validation": "required|min:0",
    "value": 0,
    "min": 0,
    "max": 10000,
    "step": 0.01,
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Email Field
```json
{
  "type": "email",
  "props": {
    "name": "email",
    "label": "Email Address",
    "placeholder": "user@example.com",
    "help": "Enter valid email",
    "validation": "required|email",
    "value": "",
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

#### 2. Selection Components

##### Select Dropdown
```json
{
  "type": "select",
  "props": {
    "name": "category",
    "label": "Category",
    "help": "Select category",
    "validation": "required",
    "value": "",
    "placeholder": "Choose an option",
    "options": [
      { "label": "Option 1", "value": "option_1" },
      { "label": "Option 2", "value": "option_2" }
    ],
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Radio Buttons
```json
{
  "type": "radio",
  "props": {
    "name": "approval_status",
    "label": "Approval Status",
    "help": "Select approval decision",
    "validation": "required",
    "value": "",
    "options": [
      { "label": "Approve", "value": "approved" },
      { "label": "Reject", "value": "rejected" },
      { "label": "Pending", "value": "pending" }
    ],
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Checkboxes
```json
{
  "type": "checkbox",
  "props": {
    "name": "requirements",
    "label": "Requirements",
    "help": "Select all that apply",
    "validation": "",
    "value": [],
    "options": [
      { "label": "Documentation", "value": "docs" },
      { "label": "Approval", "value": "approval" },
      { "label": "Review", "value": "review" }
    ],
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Switch Toggle
```json
{
  "type": "switch",
  "props": {
    "name": "is_active",
    "label": "Active Status",
    "help": "Toggle active status",
    "validation": "",
    "value": false,
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

#### 3. Date and Time Components

##### Date Picker
```json
{
  "type": "date",
  "props": {
    "name": "start_date",
    "label": "Start Date",
    "help": "Select start date",
    "validation": "required",
    "value": "",
    "min": "2024-01-01",
    "max": "2025-12-31",
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Time Picker
```json
{
  "type": "time",
  "props": {
    "name": "meeting_time",
    "label": "Meeting Time",
    "help": "Select time",
    "validation": "required",
    "value": "",
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### DateTime Picker
```json
{
  "type": "datetime-local",
  "props": {
    "name": "appointment",
    "label": "Appointment",
    "help": "Select date and time",
    "validation": "required",
    "value": "",
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

#### 4. Advanced Input Components

##### File Upload
```json
{
  "type": "file",
  "props": {
    "name": "document",
    "label": "Upload Document",
    "help": "Upload supporting documents",
    "validation": "required",
    "accept": ".pdf,.doc,.docx,.jpg,.jpeg,.png",
    "multiple": false,
    "maxSize": "10MB",
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Color Picker
```json
{
  "type": "color",
  "props": {
    "name": "theme_color",
    "label": "Theme Color",
    "help": "Select theme color",
    "validation": "",
    "value": "#3b82f6",
    "width": "25%",
    "gridColumn": "span 3",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Range Slider
```json
{
  "type": "range",
  "props": {
    "name": "priority",
    "label": "Priority Level",
    "help": "Set priority level",
    "validation": "",
    "value": 5,
    "min": 1,
    "max": 10,
    "step": 1,
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Hidden Field
```json
{
  "type": "hidden",
  "props": {
    "name": "user_id",
    "value": "12345",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Button
```json
{
  "type": "button",
  "props": {
    "name": "submit_btn",
    "label": "Submit Form",
    "buttonType": "submit",    // submit, button, reset
    "variant": "primary",      // primary, secondary, danger
    "size": "md",             // sm, md, lg
    "disabled": false,
    "width": "25%",
    "gridColumn": "span 3",
    "conditionalLogic": { /* same as above */ }
  }
}
```

#### 5. Layout Components

##### Heading
```json
{
  "type": "heading",
  "props": {
    "name": "section_title",
    "value": "Section Title",
    "level": 2,               // 1-6 heading levels
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Paragraph
```json
{
  "type": "paragraph",
  "props": {
    "name": "description_text",
    "value": "This is descriptive text content.",
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Divider
```json
{
  "type": "divider",
  "props": {
    "name": "section_divider",
    "style": "solid",         // solid, dashed, dotted
    "color": "#e5e7eb",
    "thickness": 1,
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

#### 6. Advanced Components

##### Info Display
```json
{
  "type": "info-display",
  "props": {
    "title": "Information",
    "name": "info_display_1",
    "help": "Information display",
    "layout": "vertical",      // vertical, horizontal
    "showBorder": true,
    "backgroundColor": "#f8fafc",
    "fields": [
      { "label": "Status", "value": "Active", "key": "status" },
      { "label": "Created", "value": "2024-01-01", "key": "created" }
    ],
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Image Preview
```json
{
  "type": "image-preview",
  "props": {
    "label": "Image Preview",
    "name": "image_preview_1",
    "help": "Preview image",
    "imageUrl": "https://placehold.co/600x400",
    "altText": "Preview image",
    "caption": "Image caption",
    "showZoom": true,
    "showCaption": true,
    "maxWidth": "100%",
    "height": "auto",
    "width": "50%",
    "gridColumn": "span 6",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Repeating Group
```json
{
  "type": "repeating-group",
  "props": {
    "label": "Expense Items",
    "name": "expense_items",
    "help": "Add expense items",
    "minItems": 1,
    "maxItems": 10,
    "buttonText": "Add Expense",
    "removeText": "Remove",
    "fields": [
      {
        "type": "text",
        "name": "description",
        "label": "Description",
        "placeholder": "Enter description"
      },
      {
        "type": "number",
        "name": "amount",
        "label": "Amount",
        "placeholder": "0.00"
      }
    ],
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

##### Dynamic List
```json
{
  "type": "dynamic-list",
  "props": {
    "label": "Tags",
    "name": "tags",
    "help": "Add tags",
    "placeholder": "Enter tag",
    "buttonText": "Add Tag",
    "minItems": 0,
    "maxItems": 20,
    "defaultItems": ["Tag 1", "Tag 2"],
    "width": "100%",
    "gridColumn": "span 12",
    "conditionalLogic": { /* same as above */ }
  }
}
```

## Conditional Logic Structure

### Condition Object
```json
{
  "field": "field_name",        // Target field name
  "value": "expected_value",    // Expected value
  "operator": "eq"              // Comparison operator
}
```

### Available Operators
- `"eq"`: Equal to
- `"ne"`: Not equal to
- `"gt"`: Greater than
- `"gte"`: Greater than or equal to
- `"lt"`: Less than
- `"lte"`: Less than or equal to
- `"contains"`: Contains substring
- `"not_contains"`: Does not contain substring
- `"starts_with"`: Starts with
- `"ends_with"`: Ends with
- `"in"`: Value is in array
- `"not_in"`: Value is not in array
- `"empty"`: Field is empty
- `"not_empty"`: Field is not empty

### Conditional Logic Example
```json
{
  "conditionalLogic": {
    "action": "show",
    "enabled": true,
    "operator": "and",
    "conditions": [
      {
        "field": "user_type",
        "value": "premium",
        "operator": "eq"
      },
      {
        "field": "subscription_status",
        "value": "active",
        "operator": "eq"
      }
    ]
  }
}
```

## Validation Rules

### Common Validation Rules
- `required`: Field is required
- `email`: Valid email format
- `url`: Valid URL format
- `min:n`: Minimum value/length
- `max:n`: Maximum value/length
- `between:min,max`: Value between range
- `alpha`: Only alphabetic characters
- `alphanumeric`: Only alphanumeric characters
- `numeric`: Only numeric values
- `regex:/pattern/`: Custom regex pattern

### Validation Examples
```json
{
  "validation": "required|email",
  "validation": "required|min:3|max:50",
  "validation": "required|numeric|between:1,100",
  "validation": "required|regex:/^[A-Z0-9-]+$/"
}
```

## Grid System

### Grid Column Options
- `"span 1"` to `"span 12"`: Column span (1-12)
- `"span 3"`: 25% width (3/12)
- `"span 6"`: 50% width (6/12)
- `"span 9"`: 75% width (9/12)
- `"span 12"`: 100% width (12/12)

### Width Options
- `"25%"`, `"33.33%"`, `"50%"`, `"66.67%"`, `"75%"`, `"100%"`
- Custom pixel values: `"300px"`
- Auto width: `"auto"`

## Complete Form Example

```json
{
  "formName": "Travel Reimbursement Form",
  "formDescription": "Submit your travel expenses for reimbursement",
  "formId": null,
  "components": [
    {
      "type": "heading",
      "props": {
        "name": "main_heading",
        "value": "Travel Reimbursement Request",
        "level": 1,
        "width": "100%",
        "gridColumn": "span 12",
        "conditionalLogic": {
          "action": "show",
          "enabled": false,
          "operator": "and",
          "conditions": []
        }
      }
    },
    {
      "type": "text",
      "props": {
        "name": "employee_name",
        "label": "Employee Name",
        "placeholder": "Enter your full name",
        "help": "Your full name as it appears in company records",
        "validation": "required|min:2",
        "value": "",
        "width": "50%",
        "gridColumn": "span 6",
        "conditionalLogic": {
          "action": "show",
          "enabled": false,
          "operator": "and",
          "conditions": []
        }
      }
    },
    {
      "type": "email",
      "props": {
        "name": "employee_email",
        "label": "Email Address",
        "placeholder": "employee@company.com",
        "help": "Your company email address",
        "validation": "required|email",
        "value": "",
        "width": "50%",
        "gridColumn": "span 6",
        "conditionalLogic": {
          "action": "show",
          "enabled": false,
          "operator": "and",
          "conditions": []
        }
      }
    },
    {
      "type": "number",
      "props": {
        "name": "total_amount",
        "label": "Total Amount (RM)",
        "placeholder": "0.00",
        "help": "Total reimbursement amount",
        "validation": "required|min:0.01",
        "value": 0,
        "min": 0,
        "step": 0.01,
        "width": "50%",
        "gridColumn": "span 6",
        "conditionalLogic": {
          "action": "show",
          "enabled": false,
          "operator": "and",
          "conditions": []
        }
      }
    }
  ],
  "customScript": "// Auto-calculate total when expenses change\nonFieldChange(['expense_items'], () => {\n  const expenses = getField('expense_items') || [];\n  const total = expenses.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0);\n  setField('total_amount', total.toFixed(2));\n});",
  "customCSS": ".form-container { background: #f9fafb; padding: 20px; border-radius: 8px; }",
  "formEvents": {
    "onLoad": true,
    "onFieldChange": true,
    "onSubmit": false,
    "onValidation": false
  },
  "scriptMode": "safe"
}
```

## Import/Export Usage

### Importing a Form
1. Navigate to Form Management page
2. Click "Import Form" button
3. Select JSON file or paste JSON content
4. Review the imported form structure
5. Save to create the form in database

### Exporting a Form
1. In Form Management, click "Export" on any form
2. JSON file will download with complete form structure
3. Use the exported JSON to backup or duplicate forms

### API Endpoints
- `POST /api/forms/import` - Import form from JSON
- `GET /api/forms/[id]/export` - Export form as JSON

## Best Practices

1. **Naming Convention**: Use descriptive, lowercase field names with underscores
2. **Validation**: Always include appropriate validation rules for data integrity
3. **Grid Layout**: Plan your grid layout for responsive design
4. **Conditional Logic**: Use sparingly to avoid complex dependencies
5. **Default Values**: Provide sensible defaults where appropriate
6. **Help Text**: Include helpful descriptions for complex fields
7. **Component Order**: Logical flow from top to bottom
8. **Testing**: Test forms thoroughly after import

## Troubleshooting

### Common Import Issues
1. **Missing Required Fields**: Ensure `formName` and `components` are present
2. **Invalid JSON**: Validate JSON syntax before import
3. **Component Props**: Each component needs valid `type` and `props`
4. **Grid Values**: Ensure `gridColumn` values are valid (span 1-12)
5. **Validation Syntax**: Check validation rule syntax
6. **Conditional Logic**: Verify field references in conditions exist

### Validation Errors
- Check field name uniqueness
- Verify option arrays for select/radio/checkbox components
- Ensure numeric values for min/max/step properties
- Validate conditional logic field references 