671 lines
24 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="page-title">Campaign - Alberta Influence Tool</title>
<link rel="stylesheet" href="/css/styles.css">
<style>
.campaign-header {
background: linear-gradient(135deg, #3498db, #2c3e50);
color: white;
padding: 3rem 0;
text-align: center;
margin-bottom: 2rem;
}
.campaign-header h1 {
font-size: 2.5rem;
margin-bottom: 1rem;
}
.campaign-stats {
background: #f8f9fa;
padding: 1rem;
border-radius: 8px;
text-align: center;
margin-bottom: 2rem;
border: 2px solid #e9ecef;
}
.email-count {
font-size: 2rem;
font-weight: bold;
color: #3498db;
margin-bottom: 0.5rem;
}
.campaign-content {
max-width: 800px;
margin: 0 auto;
padding: 0 1rem;
}
.call-to-action {
background: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 8px;
padding: 1.5rem;
margin-bottom: 2rem;
text-align: center;
}
.user-info-form {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 2rem;
}
.email-preview {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 1.5rem;
margin-bottom: 2rem;
}
.email-preview h3 {
color: #495057;
margin-bottom: 1rem;
}
.email-subject {
font-weight: bold;
color: #2c3e50;
margin-bottom: 1rem;
}
.email-body {
line-height: 1.6;
color: #495057;
white-space: pre-wrap;
}
.representatives-grid {
display: grid;
gap: 1rem;
margin-bottom: 2rem;
}
.rep-card {
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 1rem;
background: white;
transition: transform 0.2s, box-shadow 0.2s;
}
.rep-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.rep-info {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1rem;
}
.rep-photo {
width: 60px;
height: 60px;
border-radius: 50%;
object-fit: cover;
background: #e9ecef;
}
.rep-details h4 {
margin: 0 0 0.25rem 0;
color: #2c3e50;
}
.rep-details p {
margin: 0;
color: #6c757d;
font-size: 0.9rem;
}
.rep-actions {
display: flex;
gap: 0.5rem;
justify-content: center;
}
.email-method-toggle {
display: flex;
gap: 1rem;
justify-content: center;
margin-bottom: 1rem;
}
.method-option {
display: flex;
align-items: center;
gap: 0.5rem;
}
.progress-steps {
display: flex;
justify-content: space-between;
margin-bottom: 2rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 8px;
}
.step {
flex: 1;
text-align: center;
position: relative;
padding: 0.5rem;
}
.step.active {
color: #3498db;
font-weight: bold;
}
.step.completed {
color: #27ae60;
}
.step:not(:last-child)::after {
content: '→';
position: absolute;
right: -50%;
color: #6c757d;
}
.loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.7);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
.loading-content {
background: white;
padding: 2rem;
border-radius: 8px;
text-align: center;
}
@media (max-width: 768px) {
.campaign-header h1 {
font-size: 2rem;
}
.progress-steps {
flex-direction: column;
gap: 0.5rem;
}
.step:not(:last-child)::after {
content: '↓';
position: static;
}
}
</style>
</head>
<body>
<!-- Loading Overlay -->
<div id="loading-overlay" class="loading-overlay">
<div class="loading-content">
<div class="spinner"></div>
<p id="loading-message">Loading campaign...</p>
</div>
</div>
<!-- Campaign Header -->
<div class="campaign-header">
<div class="container">
<h1 id="campaign-title">Loading Campaign...</h1>
<p id="campaign-description"></p>
</div>
</div>
<div class="campaign-content">
<!-- Email Count Display -->
<div id="campaign-stats" class="campaign-stats" style="display: none;">
<div class="email-count" id="email-count">0</div>
<p>Albertans have sent emails through this campaign</p>
</div>
<!-- Call to Action -->
<div id="call-to-action" class="call-to-action" style="display: none;">
<!-- Content will be loaded dynamically -->
</div>
<!-- Progress Steps -->
<div class="progress-steps">
<div class="step active" id="step-info">Enter Your Info</div>
<div class="step" id="step-postal">Find Representatives</div>
<div class="step" id="step-send">Send Emails</div>
</div>
<!-- User Information Form -->
<div id="user-info-section" class="user-info-form">
<h2>Your Information</h2>
<p>We need some basic information to find your representatives and track campaign engagement.</p>
<form id="user-info-form">
<div class="form-group">
<label for="user-postal-code">Your Postal Code *</label>
<input type="text" id="user-postal-code" name="postalCode" required
placeholder="T5K 2M5" maxlength="7" style="text-transform: uppercase;">
</div>
<div id="optional-fields" style="display: none;">
<div class="form-group">
<label for="user-name">Your Name (Optional)</label>
<input type="text" id="user-name" name="userName" placeholder="Your full name">
</div>
<div class="form-group">
<label for="user-email">Your Email (Optional)</label>
<input type="email" id="user-email" name="userEmail" placeholder="your@email.com">
</div>
</div>
<button type="submit" class="btn btn-primary">Find My Representatives</button>
</form>
</div>
<!-- Email Preview -->
<div id="email-preview" class="email-preview" style="display: none;">
<h3>📧 Email Preview</h3>
<p>This is the message that will be sent to your representatives:</p>
<div class="email-subject" id="preview-subject"></div>
<div class="email-body" id="preview-body"></div>
</div>
<!-- Representatives Section -->
<div id="representatives-section" style="display: none;">
<h2>Your Representatives</h2>
<p>Select how you'd like to contact each representative:</p>
<!-- Email Method Selection -->
<div id="email-method-selection" class="email-method-toggle">
<div class="method-option">
<input type="radio" id="method-smtp" name="emailMethod" value="smtp" checked>
<label for="method-smtp">📧 Send via our system</label>
</div>
<div class="method-option">
<input type="radio" id="method-mailto" name="emailMethod" value="mailto">
<label for="method-mailto">📬 Open in your email app</label>
</div>
</div>
<div id="representatives-list" class="representatives-grid">
<!-- Representatives will be loaded here -->
</div>
</div>
<!-- Success Message -->
<div id="success-section" style="display: none; text-align: center; padding: 2rem;">
<h2 style="color: #27ae60;">🎉 Thank you for taking action!</h2>
<p>Your emails have been processed. Democracy works when people like you get involved.</p>
<button class="btn btn-secondary" data-action="reload-page">Send More Emails</button>
</div>
<!-- Error Messages -->
<div id="error-message" class="error-message" style="display: none;"></div>
</div>
<script>
class CampaignPage {
constructor() {
this.campaign = null;
this.representatives = [];
this.userInfo = {};
this.currentStep = 1;
this.init();
}
init() {
// Get campaign slug from URL
const pathParts = window.location.pathname.split('/');
this.campaignSlug = pathParts[pathParts.length - 1];
// Set up form handlers
document.getElementById('user-info-form').addEventListener('submit', (e) => {
this.handleUserInfoSubmit(e);
});
// Postal code formatting
document.getElementById('user-postal-code').addEventListener('input', (e) => {
this.formatPostalCode(e);
});
// Load campaign data
this.loadCampaign();
}
async loadCampaign() {
this.showLoading('Loading campaign...');
try {
const response = await fetch(`/api/campaigns/${this.campaignSlug}`);
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'Failed to load campaign');
}
this.campaign = data.campaign;
this.renderCampaign();
} catch (error) {
this.showError('Failed to load campaign: ' + error.message);
} finally {
this.hideLoading();
}
}
renderCampaign() {
// Update page title and meta
document.getElementById('page-title').textContent = this.campaign.title + ' - Alberta Influence Tool';
document.getElementById('campaign-title').textContent = this.campaign.title;
document.getElementById('campaign-description').textContent = this.campaign.description || '';
// Show email count if enabled
if (this.campaign.show_email_count && this.campaign.emailCount !== null) {
document.getElementById('email-count').textContent = this.campaign.emailCount;
document.getElementById('campaign-stats').style.display = 'block';
}
// Show call to action if present
if (this.campaign.call_to_action) {
document.getElementById('call-to-action').innerHTML = `<p>${this.campaign.call_to_action}</p>`;
document.getElementById('call-to-action').style.display = 'block';
}
// Show/hide optional user info fields
if (this.campaign.collect_user_info) {
document.getElementById('optional-fields').style.display = 'block';
}
// Show email preview
document.getElementById('preview-subject').textContent = this.campaign.email_subject;
document.getElementById('preview-body').textContent = this.campaign.email_body;
document.getElementById('email-preview').style.display = 'block';
// Configure email method options
if (!this.campaign.allow_smtp_email) {
document.getElementById('method-smtp').disabled = true;
document.getElementById('method-mailto').checked = true;
}
if (!this.campaign.allow_mailto_link) {
document.getElementById('method-mailto').disabled = true;
document.getElementById('method-smtp').checked = true;
}
}
formatPostalCode(e) {
let value = e.target.value.replace(/\s/g, '').toUpperCase();
if (value.length > 3) {
value = value.substring(0, 3) + ' ' + value.substring(3, 6);
}
e.target.value = value;
}
async handleUserInfoSubmit(e) {
e.preventDefault();
const formData = new FormData(e.target);
this.userInfo = {
postalCode: formData.get('postalCode').replace(/\s/g, '').toUpperCase(),
userName: formData.get('userName') || '',
userEmail: formData.get('userEmail') || ''
};
await this.loadRepresentatives();
}
async loadRepresentatives() {
this.showLoading('Finding your representatives...');
try {
const response = await fetch(`/api/campaigns/${this.campaignSlug}/representatives/${this.userInfo.postalCode}`);
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'Failed to load representatives');
}
this.representatives = data.representatives;
this.renderRepresentatives();
this.setStep(2);
// Scroll to representatives section
document.getElementById('representatives-section').scrollIntoView({
behavior: 'smooth'
});
} catch (error) {
this.showError('Failed to load representatives: ' + error.message);
} finally {
this.hideLoading();
}
}
renderRepresentatives() {
const list = document.getElementById('representatives-list');
if (this.representatives.length === 0) {
list.innerHTML = '<p>No representatives found for your area. Please check your postal code.</p>';
return;
}
list.innerHTML = this.representatives.map(rep => `
<div class="rep-card">
<div class="rep-info">
${rep.photo_url ?
`<img src="${rep.photo_url}" alt="${rep.name}" class="rep-photo">` :
`<div class="rep-photo"></div>`
}
<div class="rep-details">
<h4>${rep.name}</h4>
<p>${rep.elected_office || 'Representative'}</p>
<p>${rep.party_name || ''}</p>
${rep.email ? `<p>📧 ${rep.email}</p>` : ''}
</div>
</div>
${rep.email ? `
<div class="rep-actions">
<button class="btn btn-primary" data-action="send-email"
data-email="${rep.email}"
data-name="${rep.name}"
data-title="${rep.elected_office || ''}"
data-level="${this.getGovernmentLevel(rep)}">
Send Email
</button>
</div>
` : '<p style="text-align: center; color: #6c757d;">No email available</p>'}
</div>
`).join('');
// Attach event listeners to send email buttons
this.attachEmailButtonListeners();
document.getElementById('representatives-section').style.display = 'block';
}
attachEmailButtonListeners() {
// Send email buttons
document.querySelectorAll('[data-action="send-email"]').forEach(btn => {
btn.addEventListener('click', (e) => {
const email = e.target.dataset.email;
const name = e.target.dataset.name;
const title = e.target.dataset.title;
const level = e.target.dataset.level;
this.sendEmail(email, name, title, level);
});
});
// Reload page button
const reloadBtn = document.querySelector('[data-action="reload-page"]');
if (reloadBtn) {
reloadBtn.addEventListener('click', () => {
location.reload();
});
}
}
getGovernmentLevel(rep) {
const office = (rep.elected_office || '').toLowerCase();
if (office.includes('mp') || office.includes('member of parliament')) return 'Federal';
if (office.includes('mla') || office.includes('legislative assembly')) return 'Provincial';
if (office.includes('mayor') || office.includes('councillor')) return 'Municipal';
if (office.includes('school')) return 'School Board';
return 'Other';
}
async sendEmail(recipientEmail, recipientName, recipientTitle, recipientLevel) {
const emailMethod = document.querySelector('input[name="emailMethod"]:checked').value;
if (emailMethod === 'mailto') {
this.openMailtoLink(recipientEmail);
} else {
await this.sendSMTPEmail(recipientEmail, recipientName, recipientTitle, recipientLevel);
}
}
openMailtoLink(recipientEmail) {
const subject = encodeURIComponent(this.campaign.email_subject);
const body = encodeURIComponent(this.campaign.email_body);
const mailtoUrl = `mailto:${recipientEmail}?subject=${subject}&body=${body}`;
// Track the mailto click
this.trackEmail(recipientEmail, '', '', '', 'mailto');
window.open(mailtoUrl);
}
async sendSMTPEmail(recipientEmail, recipientName, recipientTitle, recipientLevel) {
this.showLoading('Sending email...');
try {
const response = await fetch(`/api/campaigns/${this.campaignSlug}/send-email`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userEmail: this.userInfo.userEmail,
userName: this.userInfo.userName,
postalCode: this.userInfo.postalCode,
recipientEmail,
recipientName,
recipientTitle,
recipientLevel,
emailMethod: 'smtp'
})
});
const data = await response.json();
if (data.success) {
this.showSuccess('Email sent successfully!');
} else {
throw new Error(data.error || 'Failed to send email');
}
} catch (error) {
this.showError('Failed to send email: ' + error.message);
} finally {
this.hideLoading();
}
}
async trackEmail(recipientEmail, recipientName, recipientTitle, recipientLevel, emailMethod) {
try {
await fetch(`/api/campaigns/${this.campaignSlug}/send-email`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userEmail: this.userInfo.userEmail,
userName: this.userInfo.userName,
postalCode: this.userInfo.postalCode,
recipientEmail,
recipientName,
recipientTitle,
recipientLevel,
emailMethod
})
});
} catch (error) {
console.error('Failed to track email:', error);
}
}
setStep(step) {
// Reset all steps
document.querySelectorAll('.step').forEach(s => {
s.classList.remove('active', 'completed');
});
// Mark completed steps
for (let i = 1; i < step; i++) {
document.getElementById(`step-${this.getStepName(i)}`).classList.add('completed');
}
// Mark current step
document.getElementById(`step-${this.getStepName(step)}`).classList.add('active');
this.currentStep = step;
}
getStepName(step) {
const steps = ['', 'info', 'postal', 'send'];
return steps[step] || 'info';
}
showLoading(message) {
document.getElementById('loading-message').textContent = message;
document.getElementById('loading-overlay').style.display = 'flex';
}
hideLoading() {
document.getElementById('loading-overlay').style.display = 'none';
}
showError(message) {
const errorDiv = document.getElementById('error-message');
errorDiv.textContent = message;
errorDiv.style.display = 'block';
setTimeout(() => {
errorDiv.style.display = 'none';
}, 5000);
}
showSuccess(message) {
// Update email count if enabled
if (this.campaign.show_email_count) {
const countElement = document.getElementById('email-count');
const currentCount = parseInt(countElement.textContent) || 0;
countElement.textContent = currentCount + 1;
}
// You could show a toast or update UI to indicate success
alert(message); // Simple for now, could be improved with better UI
}
}
// Initialize the campaign page
let campaignPage;
document.addEventListener('DOMContentLoaded', () => {
campaignPage = new CampaignPage();
});
</script>
</body>
</html>