# Frontend Integration Guide - Phase 1 Daily Helper

This guide explains how to integrate Phase 1 Daily Helper components into your React application.

## Quick Start

### 1. Import Components

```typescript
import NotificationCenter from './components/NotificationCenter'
import UserProfileSetup from './components/UserProfileSetup'
import HabitTracker from './components/HabitTracker'
import DailyChecklistPanel from './components/DailyChecklistPanel'
```

### 2. Add Notification Center to Header

The NotificationCenter should be displayed in your main header/navbar:

```typescript
<header>
  <h1>Trading Dashboard</h1>
  <NotificationCenter />  {/* Bell icon with unread count */}
</header>
```

### 3. Create Daily Helper Tab

Add a new tab to your application that displays the daily helper components:

```typescript
{activeTab === 'Daily Helper' && (
  <div style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))' }}>
    <div>
      <button onClick={() => setShowProfileSetup(true)}>
        ⚙️ Setup Profile
      </button>
      <DailyChecklistPanel checklistType="morning" />
    </div>
    <div>
      <HabitTracker />
    </div>
  </div>
)}

{showProfileSetup && (
  <UserProfileSetup
    onClose={() => setShowProfileSetup(false)}
    onSaved={() => {
      // Handle successful profile save
    }}
  />
)}
```

## Component Details

### NotificationCenter

**Location:** Top-right of your header

**Features:**
- Bell icon with unread badge
- Dropdown notification panel
- Auto-refreshes every 30 seconds
- Mark as read/unread
- Delete notifications

**Props:**
- None (uses API directly)

**Example:**
```typescript
<NotificationCenter />
```

### UserProfileSetup

**Location:** Modal dialog

**Features:**
- Complete user profile configuration
- Timezone selection
- Trading style selection
- Risk tolerance configuration
- Notification preferences
- Email and phone settings

**Props:**
```typescript
interface UserProfileSetupProps {
  onClose: () => void
  onSaved?: (profile: UserProfile) => void
}
```

**Example:**
```typescript
const [showSetup, setShowSetup] = useState(false)

{showSetup && (
  <UserProfileSetup
    onClose={() => setShowSetup(false)}
    onSaved={(profile) => console.log('Profile saved:', profile)}
  />
)}
```

### DailyChecklistPanel

**Location:** Main content area

**Features:**
- Interactive checklist with toggleable items
- Completion percentage progress bar
- Add/remove items
- Notes section
- Default templates for morning/active/evening

**Props:**
```typescript
interface DailyChecklistPanelProps {
  checklistType?: 'morning' | 'active_trading' | 'evening' | 'all'
}
```

**Example:**
```typescript
<DailyChecklistPanel checklistType="morning" />
<DailyChecklistPanel checklistType="evening" />
<DailyChecklistPanel checklistType="active_trading" />
```

### HabitTracker

**Location:** Main content area

**Features:**
- Create and manage habits
- Streak counter with 🔥 emojis
- Completion logging
- Statistics display
- Motivational messages

**Props:**
- None (uses API directly)

**Example:**
```typescript
<HabitTracker />
```

## API Endpoints Used

All components communicate with these API endpoints:

### User Profile
```
POST   /api/daily-helper/profile
GET    /api/daily-helper/profile
PUT    /api/daily-helper/profile
DELETE /api/daily-helper/profile
```

### Notifications
```
POST   /api/daily-helper/notifications
GET    /api/daily-helper/notifications
GET    /api/daily-helper/notifications/{id}
PUT    /api/daily-helper/notifications/{id}/read
POST   /api/daily-helper/notifications/mark-all-read
DELETE /api/daily-helper/notifications/{id}
```

### Checklists
```
POST   /api/daily-helper/checklists
GET    /api/daily-helper/checklists/today
GET    /api/daily-helper/checklists
GET    /api/daily-helper/checklists/{id}
PUT    /api/daily-helper/checklists/{id}
PUT    /api/daily-helper/checklists/{id}/items/{item_id}
DELETE /api/daily-helper/checklists/{id}
```

### Habits
```
POST   /api/daily-helper/habits
GET    /api/daily-helper/habits
GET    /api/daily-helper/habits/{id}
POST   /api/daily-helper/habits/{id}/log
DELETE /api/daily-helper/habits/{id}
```

## Complete Example App.tsx

```typescript
import { useEffect, useState } from 'react'
import NotificationCenter from './components/NotificationCenter'
import UserProfileSetup from './components/UserProfileSetup'
import HabitTracker from './components/HabitTracker'
import DailyChecklistPanel from './components/DailyChecklistPanel'
import LiveMarketPanel from './components/LiveMarketPanel'

export default function App() {
  const [activeTab, setActiveTab] = useState<
    'Live' | 'Daily Helper' | 'Settings'
  >('Live')
  const [showProfileSetup, setShowProfileSetup] = useState(false)

  return (
    <div className="min-h-screen bg-dark-bg p-6">
      <div className="max-w-[1400px] mx-auto">
        {/* Header */}
        <header className="mb-6 flex items-center justify-between">
          <h1 className="text-3xl font-bold">Trading Dashboard</h1>
          <NotificationCenter />
        </header>

        {/* Tabs */}
        <div className="flex gap-4 mb-6">
          {['Live', 'Daily Helper', 'Settings'].map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab as any)}
              className={`px-4 py-2 rounded ${
                activeTab === tab
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-700 text-gray-300'
              }`}
            >
              {tab}
            </button>
          ))}
        </div>

        {/* Content */}
        {activeTab === 'Live' && <LiveMarketPanel />}

        {activeTab === 'Daily Helper' && (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div>
              <button
                onClick={() => setShowProfileSetup(true)}
                className="mb-4 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded"
              >
                ⚙️ Setup Profile
              </button>
              <DailyChecklistPanel checklistType="morning" />
            </div>
            <div>
              <HabitTracker />
            </div>
          </div>
        )}

        {/* Profile Setup Modal */}
        {showProfileSetup && (
          <UserProfileSetup
            onClose={() => setShowProfileSetup(false)}
            onSaved={() => {
              setShowProfileSetup(false)
              // Refresh any related data if needed
            }}
          />
        )}
      </div>
    </div>
  )
}
```

## Styling

All Phase 1 components use:
- **TailwindCSS** for styling
- **Dark theme** (gray-900, gray-800 backgrounds)
- **Blue accents** (#667eea primary color)
- **Responsive design** (mobile-friendly)

### Custom CSS (if needed)

```css
/* Dark theme */
:root {
  --color-bg: #111827;
  --color-surface: #1f2937;
  --color-border: #374151;
  --color-text: #f3f4f6;
  --color-primary: #667eea;
}

.daily-helper-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 16px;
}

.daily-helper-card {
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: 8px;
  padding: 24px;
}
```

## Error Handling

All components have built-in error handling with user-friendly messages. If an API call fails:

1. User sees an error message
2. Components remain functional
3. Retry buttons are provided
4. No silent failures

## Performance Tips

1. **Lazy Load Components**
   ```typescript
   const NotificationCenter = React.lazy(
     () => import('./components/NotificationCenter')
   )
   ```

2. **Use Suspense**
   ```typescript
   <Suspense fallback={<div>Loading...</div>}>
     <NotificationCenter />
   </Suspense>
   ```

3. **Memoize Components**
   ```typescript
   export default React.memo(DailyChecklistPanel)
   ```

## Customization

### Change Default Checklist Type

```typescript
<DailyChecklistPanel checklistType="evening" />
```

### Customize Colors

Modify component imports and update color classes:

```typescript
// Change from gray-900 to custom color
className="bg-custom-dark"
```

### Add Custom Callbacks

```typescript
const [checklist, setChecklist] = useState(null)

<DailyChecklistPanel
  checklistType="morning"
  onItemComplete={(itemId) => {
    console.log('Item completed:', itemId)
  }}
/>
```

## Troubleshooting

### Notifications Not Showing?
- Check that backend is running
- Verify API endpoint: `http://localhost:8000/api/daily-helper/notifications`
- Check browser console for errors

### Checklist Not Persisting?
- Ensure database is initialized (run migration)
- Check that API is responding with 200
- Clear browser cache and reload

### Profile Not Saving?
- Verify email format is valid
- Check backend logs for validation errors
- Ensure profile API is accessible

## Next Steps

1. **Customize the components** to match your branding
2. **Add more features** like custom checklist items
3. **Integrate with your existing dashboard**
4. **Set up automated routines** (Phase 2)
5. **Implement email reports** (Phase 2)

## Support

For issues or questions:
1. Check API responses in browser DevTools
2. Review backend logs at `backend/app/main.py`
3. Verify database is initialized
4. See `MIGRATION_INSTRUCTIONS.md` for database setup

---

**Ready to go!** Your Daily Helper components are now fully integrated. 🚀
