# Design System Swarm - Quick Start Guide

**Current Status**: ✅ System Running  
**Backend**: http://localhost:3001  
**Frontend**: http://localhost:3456

---

## What's Working

### ✅ Backend API Server
- Running on `http://localhost:3001`
- All endpoints protected with JWT authentication
- SQLite database initialized with default "test" project
- Real-time socket.io support

### ✅ Frontend Admin UI
- Running on `http://localhost:3456`
- Web Components with native event handling
- Hot module reloading enabled
- Project selector component fully functional

### ✅ Database
- Fresh SQLite database at `server/data/design-system.db`
- Default project "test" created
- All models synchronized

### ✅ Architecture Fixes
- **Phase 1**: Incognito-detector lazy initialization ✅
- **Phase 2**: Context-store circular dependency removed ✅
- **Phase 3**: API-client updated with lazy functions ✅
- **Phase 4**: Project-selector memory leaks fixed ✅

---

## Open in Browser

### Admin UI
```
http://localhost:3456
```

**Expected Behavior**:
1. Page loads with "Select a Project" modal
2. Project selector shows "test" project in dropdown
3. Click on project or modal button to select
4. Modal closes, project persists in header

---

## Server Management

### Start Backend (from `/server` directory)
```bash
npm start
```

### Start Frontend (from `/admin-ui` directory)
```bash
npm run dev
```

### Stop Servers
- Press `Ctrl+C` in respective terminal windows
- Or kill processes: `lsof -i :3001` and `lsof -i :3456`

---

## File Locations

### Backend
- **Main Server**: `server/src/server.js`
- **Database**: `server/data/design-system.db`
- **Config**: `server/.env`

### Frontend
- **Entry Point**: `admin-ui/index.html`
- **Main App**: `admin-ui/js/app.js`
- **Components**: `admin-ui/js/components/`
- **Services**: `admin-ui/js/services/`
- **Stores**: `admin-ui/js/stores/`
- **Utils**: `admin-ui/js/utils/`

---

## Key Components

### Project Selector
**File**: `admin-ui/js/components/layout/ds-project-selector.js`

**Features**:
- Loads projects from authenticated API
- Dropdown selection with project details
- Modal prompt when no project selected
- Project persistence in localStorage
- Auto-reload on auth changes

### API Client
**File**: `admin-ui/js/services/api-client.js`

**Features**:
- Centralized API requests
- JWT token management
- Automatic token refresh
- Authorization header injection
- Incognito mode support (sessionStorage)

### Context Store
**File**: `admin-ui/js/stores/context-store.js`

**Features**:
- Global state management
- Event-based subscriptions
- localStorage persistence
- Page context for AI assistant

---

## Testing the System

### Quick Manual Test
1. Open http://localhost:3456
2. Verify "Select a Project" modal appears
3. Click on "test" project
4. Verify modal closes and project shows in header
5. Open browser DevTools (F12)
6. Check Network tab for Authorization headers
7. Check Console for no cascading errors

### API Test (with curl)
```bash
# Get projects endpoint (requires token - currently returns 401, which is correct)
curl http://localhost:3001/api/projects

# Output: {"status":"error","code":"UNAUTHORIZED","message":"No token provided"}
```

---

## Troubleshooting

### Port Already in Use
```bash
# Find process using port
lsof -i :3001  # Backend
lsof -i :3456  # Frontend

# Kill process (replace PID with actual process ID)
kill -9 <PID>
```

### Database Issues
```bash
# Recreate database (backend will reinitialize on startup)
rm server/data/design-system.db
npm start  # in server directory
```

### Module Not Found Errors
```bash
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install
```

### Blank Admin UI Page
- Check browser console (F12) for errors
- Verify backend is running on port 3001
- Check Network tab for failed requests
- Look for Authorization header in requests

---

## Documentation

### Comprehensive Docs
- **Architecture**: `.dss/COMPREHENSIVE_REDESIGN_COMPLETED.md`
- **System Status**: `.dss/SYSTEM_READY_FOR_TESTING.md`
- **This Guide**: `.dss/QUICK_START_GUIDE.md`

### Code Documentation
- Backend routes in `server/src/routes/`
- Component JSDoc comments in each file
- Store interface in `admin-ui/js/stores/context-store.js`

---

## Project Structure

```
dss/
├── server/                    # Backend API
│   ├── src/
│   │   ├── server.js         # Express app
│   │   ├── routes/           # API endpoints
│   │   ├── models/           # Sequelize models
│   │   └── config/           # Configuration
│   ├── data/                 # SQLite database
│   └── package.json          # Dependencies
│
├── admin-ui/                 # Frontend
│   ├── index.html            # Entry HTML
│   ├── js/
│   │   ├── app.js            # App initialization
│   │   ├── components/       # Web Components
│   │   ├── services/         # API services
│   │   ├── stores/           # State management
│   │   └── utils/            # Utilities
│   ├── styles/               # CSS files
│   └── package.json          # Dependencies
│
└── .dss/                     # Documentation
    ├── COMPREHENSIVE_REDESIGN_COMPLETED.md
    ├── SYSTEM_READY_FOR_TESTING.md
    └── QUICK_START_GUIDE.md   # This file
```

---

## Browser DevTools Tips

### Check Project Selector State
Open Console and run:
```javascript
// Get component instance
const selector = document.querySelector('ds-project-selector');

// Check projects
console.log(selector.projects);

// Check selected project
console.log(selector.selectedProject);

// Check context store
import contextStore from './admin-ui/js/stores/context-store.js';
console.log(contextStore.getState());
```

### Monitor Network Requests
1. Open DevTools → Network tab
2. Look for requests to `/api/projects`
3. Verify `Authorization: Bearer <token>` header is present
4. Check response includes project list

### Check Local Storage
DevTools → Application → Local Storage → http://localhost:3456

**Keys to Look For**:
- `auth_tokens`: JWT tokens
- `current_project_id`: Selected project
- `current_team_id`: Current team
- `current_user_id`: Current user

---

## Common Tasks

### Create a New Project (via API)
Requires authentication token first. See API documentation for details.

### Change Theme
Currently supports "default" skin. Additional skins can be added through project configuration.

### Access Admin Settings
Settings available through context store:
```javascript
contextStore.getAdminSettings()
```

### Monitor Auth Changes
```javascript
document.addEventListener('auth-change', (event) => {
  console.log('Auth state changed:', event.detail);
});
```

---

## Next Steps

### For Development
1. Explore component patterns in `admin-ui/js/components/`
2. Add new API endpoints in `server/src/routes/`
3. Create new components extending HTMLElement
4. Use context store for global state needs

### For Testing
1. Run manual functional tests
2. Test in incognito/private mode
3. Verify token refresh on 403 errors
4. Check memory leaks (DevTools → Memory)

### For Production
- [ ] Enable HTTPS
- [ ] Configure environment variables
- [ ] Set proper CORS origins
- [ ] Enable rate limiting
- [ ] Setup proper error monitoring

---

## Getting Help

### Check Logs
- **Backend**: `npm start` output (or redirect to file)
- **Frontend**: Browser console (F12)
- **Database**: SQLite logs in data directory

### Review Documentation
- See `.dss/COMPREHENSIVE_REDESIGN_COMPLETED.md` for architecture details
- See `.dss/SYSTEM_READY_FOR_TESTING.md` for current status

### Debug Cascading Failures
If system isn't working, check:
1. Module initialization order (lazy vs eager)
2. Circular dependencies (use depcheck)
3. Event listener cleanup in disconnectedCallback
4. Token persistence in storage

---

## System Health Checks

Run these to verify everything is working:

```bash
# Check backend is running
curl http://localhost:3001/api/projects -s | head

# Check frontend is running
curl http://localhost:3456 -s | head

# Check database exists
ls -la server/data/design-system.db

# Check processes
ps aux | grep -E "(npm|node|vite)" | grep -v grep
```

---

**Last Updated**: 2025-12-08  
**Status**: ✅ READY FOR TESTING

For comprehensive documentation, see `COMPREHENSIVE_REDESIGN_COMPLETED.md`
