# Local Development Guide - Polio Eradication Globe

## Quick Start

### Prerequisites
- Modern web browser (Chrome, Firefox, Safari, Edge)
- Mapbox account and access token (free tier available)
- Local web server (optional but recommended)

### Setup Steps

1. **Get Mapbox Access Token**
   - Visit https://account.mapbox.com/
   - Sign up for free account (50,000 map loads/month free)
   - Copy your default public token from the account dashboard

2. **Configure Token**
   Open `src/index.js` and replace the placeholder token:
   ```javascript
   mapboxgl.accessToken = 'pk.eyJ1IjoieW91cnVzZXJuYW1lIiwiYSI6InlvdXJ0b2tlbiJ9.yourtokenstring';
   ```

   Replace with your actual token:
   ```javascript
   mapboxgl.accessToken = 'pk.eyJ1IjoiYWN0dWFsdXNlciIsImEiOiJjbHh5ejEyMzQifQ.actual_token_here';
   ```

3. **Run Locally**

   **Option A - Python Simple Server** (Recommended):
   ```bash
   # Python 3
   python3 -m http.server 8000

   # Python 2
   python -m SimpleHTTPServer 8000
   ```
   Then visit: http://localhost:8000

   **Option B - Node.js http-server**:
   ```bash
   npx http-server -p 8000
   ```
   Then visit: http://localhost:8000

   **Option C - Direct File Open** (May have CORS issues):
   - Double-click `index.html`
   - Or drag into browser window
   - Note: ES6 modules may not work with file:// protocol in some browsers

4. **Verify It Works**
   - You should see a 3D globe with country data
   - Timeline slider should be visible at bottom
   - Click any country to see popup with vaccination data
   - Use play button to animate through years

## Project Structure

```
mapbox_globe_10/
├── index.html              # Main HTML file with UI and styling
├── src/
│   ├── index.js           # Main JavaScript logic and Mapbox setup
│   └── data/
│       └── data.js        # GeoJSON data with vaccination coverage
├── README.md              # Project documentation and data sources
└── CLAUDE.md              # This file - development guide
```

## Development Workflow

### Modifying Data

**To add a new country**, edit `src/data/data.js`:

```javascript
{
    "type": "Feature",
    "geometry": {
        "type": "Polygon",
        "coordinates": [[[lon1, lat1], [lon2, lat2], ...]]
    },
    "properties": {
        "name": "Country Name",
        "coverage_1980": 25,
        "coverage_1985": 35,
        "coverage_1990": 50,
        "coverage_1995": 65,
        "coverage_2000": 78,
        "coverage_2005": 85,
        "coverage_2010": 90,
        "coverage_2015": 93,
        "coverage_2020": 95,
        "polio_free_year": 2014,  // or null
        "endemic": false
    }
}
```

**Note**: Coordinates are simplified polygons. For production, use actual GeoJSON country boundaries from sources like Natural Earth.

### Modifying Visualization

**Change color scheme** in `src/index.js`, function `getCoverageColor()`:
```javascript
if (coverage >= 80) return '#4caf50';  // Change colors here
if (coverage >= 60) return '#8bc34a';
if (coverage >= 40) return '#ffeb3b';
if (coverage >= 20) return '#ff9800';
return '#f44336';
```

**Adjust timeline animation speed** in `src/index.js`:
```javascript
animationInterval = setInterval(() => {
    // ...
}, 800);  // Change interval (in milliseconds)
```

**Add new milestone years** in `src/index.js`:
```javascript
const milestones = {
    1980: "Your milestone text here",
    1985: "Another milestone...",
    // Add more years...
};
```

### Styling Changes

All CSS is inline in `index.html` within `<style>` tags. Key sections:

- `.info-panel` - Top left information panel
- `.timeline-control` - Bottom timeline scrubber
- `.legend` - Bottom right color legend
- `.mapboxgl-popup-content` - Country click popups

### Adding Features

**To add new interactivity**:

1. Add UI elements in `index.html`
2. Add event listeners in `src/index.js`
3. Update map styling in the `updateMapForYear()` function

**Example - Add year markers to timeline**:
```javascript
// In index.html, add to .timeline-control
<div class="year-markers">
  <span data-year="1980">1980</span>
  <span data-year="1988">GPEI</span>
  <span data-year="2020">2020</span>
</div>

// In src/index.js, add click handlers
document.querySelectorAll('.year-markers span').forEach(marker => {
    marker.addEventListener('click', (e) => {
        const year = parseInt(e.target.dataset.year);
        updateMapForYear(year);
    });
});
```

## Debugging

### Common Issues

**1. Blank map or "Style is not done loading" error**
- Check your Mapbox token is valid
- Ensure you have internet connection (Mapbox tiles load from CDN)
- Check browser console for errors

**2. No data showing on map**
- Verify `src/data/data.js` exports `polioData` correctly
- Check import in `src/index.js` matches export name
- Ensure GeoJSON structure is valid

**3. Animation not working**
- Check browser console for JavaScript errors
- Verify all DOM elements exist before adding event listeners
- Check that year range (1980-2020) matches data years

**4. ES6 Module errors with file:// protocol**
- Use a local web server instead of opening file directly
- Some browsers block ES6 modules from file:// for security

### Browser DevTools Tips

**Console useful commands**:
```javascript
// Check current year
console.log(currentYear);

// Manually trigger year update
updateMapForYear(1995);

// Check data loaded
console.log(polioData);

// Check map style loaded
console.log(map.isStyleLoaded());
```

**Inspect map layers**:
```javascript
// List all layers
console.log(map.getStyle().layers);

// Check specific layer properties
console.log(map.getPaintProperty('country-fills', 'fill-color'));
```

## Performance Optimization

### For Large Datasets

If adding more countries or data points:

1. **Use vector tiles instead of GeoJSON**:
   - Upload data to Mapbox Studio
   - Reference as tileset in map style
   - Much faster for 100+ countries

2. **Simplify geometries**:
   - Use tools like mapshaper to reduce polygon complexity
   - Balance visual quality vs. file size

3. **Debounce timeline updates**:
   ```javascript
   let timeoutId;
   slider.addEventListener('input', (e) => {
       clearTimeout(timeoutId);
       timeoutId = setTimeout(() => {
           updateMapForYear(parseInt(e.target.value));
       }, 50);
   });
   ```

## Deployment

### Static Hosting

This is a static site - no backend needed. Deploy to:

**Netlify** (drag & drop):
1. Drag `mapbox_globe_10` folder to netlify.com/drop
2. Site goes live instantly

**GitHub Pages**:
1. Push to GitHub repository
2. Settings → Pages → Deploy from main branch
3. Access at `https://username.github.io/repo-name/`

**Vercel**:
1. Install Vercel CLI: `npm i -g vercel`
2. Run `vercel` in project directory
3. Follow prompts

### Environment Variables

For production, use environment variables for Mapbox token:

```javascript
// In src/index.js
mapboxgl.accessToken = process.env.MAPBOX_TOKEN || 'fallback-token';
```

Configure in your hosting platform's environment settings.

## Data Updates

### Adding Future Years

When 2021+ data becomes available:

1. Update `src/data/data.js` - add `coverage_2021` etc. properties
2. Update timeline range in `index.html`:
   ```html
   <input type="range" min="1980" max="2025" ...>
   ```
3. Update `getCoverageForYear()` to handle new years
4. Add new milestones if any regions certified

### Real-time Data Integration

To fetch live data from WHO API:

```javascript
// Example integration
async function fetchLatestData() {
    const response = await fetch('https://api.who.int/...');
    const data = await response.json();
    // Transform to GeoJSON format
    // Update map source
    map.getSource('countries').setData(transformedData);
}
```

## Testing

### Manual Testing Checklist

- [ ] Timeline slider moves smoothly through all years
- [ ] Play/pause button toggles correctly
- [ ] Reset button returns to 1980
- [ ] All countries clickable and show correct data
- [ ] Popup shows accurate coverage percentages
- [ ] Endemic countries highlighted in 2020
- [ ] Certified countries show green border after certification year
- [ ] Statistics panel updates correctly
- [ ] Globe rotates automatically
- [ ] Rotation pauses during user interaction
- [ ] Responsive on mobile (test touch events)

### Browser Compatibility

Tested on:
- Chrome 90+ ✓
- Firefox 88+ ✓
- Safari 14+ ✓
- Edge 90+ ✓

**Note**: IE11 not supported (ES6 features used)

## Further Resources

- **Mapbox GL JS Docs**: https://docs.mapbox.com/mapbox-gl-js/
- **WHO Immunization Data**: https://www.who.int/teams/immunization-vaccines-and-biologicals/immunization-analysis-and-insights/global-monitoring/immunization-coverage/who-unicef-estimates-of-national-immunization-coverage
- **GPEI Data**: https://polioeradication.org/polio-today/polio-now/
- **GeoJSON Spec**: https://geojson.org/
- **Natural Earth Data**: https://www.naturalearthdata.com/ (for country boundaries)

## Contributing

To extend this visualization:

1. Fork/copy the project
2. Make your changes
3. Test across browsers
4. Update this CLAUDE.md with any new setup steps
5. Update README.md with new features

## License

This is an educational visualization. Data sources have their own licenses:
- WHO/UNICEF data: Public domain
- Mapbox: Requires free account and attribution
- Code: Use freely for educational purposes

---

**Questions or Issues?**

Check browser console for errors first. Most issues are:
1. Invalid/missing Mapbox token
2. CORS issues (use web server, not file://)
3. Typos in data structure
