-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrewards.html
More file actions
393 lines (362 loc) · 17.5 KB
/
rewards.html
File metadata and controls
393 lines (362 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Rewards & Points — Sustainable Food Tracker</title>
<style>
:root{
--page-bg:#fbf9f7;
--hero-start:#f6a623;
--hero-end:#f4a43a;
--card:#ffffff;
--muted:#7a8a85;
--accent-blue:#11a0f2;
--accent-green:#12b07a;
--gold:#f6a623;
--soft-shadow:0 10px 30px rgba(16,40,30,0.06);
--radius:14px;
font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial;
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;
background:var(--page-bg);
color:#16302f;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;
line-height:1.35;
}
/* HERO */
.hero{
background: linear-gradient(180deg,var(--hero-start),var(--hero-end));
padding:28px 18px 36px;
color:#fff;
border-bottom-left-radius:26px;
border-bottom-right-radius:26px;
}
.container{
width:100%;
max-width:980px;
margin:0 auto;
}
.hero-top{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.hero-top h1{margin:0;font-size:22px;font-weight:700}
.hero-sub{margin:6px 0 0;font-size:13px;opacity:0.95}
.points-card{
margin:18px auto 0;
max-width:460px;
background: rgba(255,255,255,0.12);
border-radius:14px;
padding:26px 20px;
text-align:center;
box-shadow: 0 12px 30px rgba(0,0,0,0.06);
}
.points-card .num{font-size:34px;font-weight:800}
.points-card .label{font-size:13px;opacity:0.95;margin-top:6px}
/* main */
main{max-width:980px;margin:28px auto 120px;padding:0 18px}
h2.section-title{font-size:18px;margin:6px 6px 18px;font-weight:700;color:#16302f}
/* Achievements list */
.achievements{display:flex;flex-direction:column;gap:14px;max-width:720px;margin:0 auto}
.achievement{
display:flex;
gap:14px;
background:var(--card);
border-radius:12px;
padding:14px 16px;
align-items:center;
box-shadow:var(--soft-shadow);
border:1px solid rgba(10,20,18,0.03);
}
.ach-icon{
width:54px;height:54px;border-radius:12px;background:rgba(0,0,0,0.03);display:flex;align-items:center;justify-content:center;font-size:20px;color:var(--muted);
flex-shrink:0;
}
.ach-body{flex:1;display:flex;flex-direction:column;gap:6px}
.ach-title{font-weight:700}
.ach-desc{color:var(--muted);font-size:13px}
.progress-row{display:flex;align-items:center;gap:12px;margin-top:4px}
.progress-bg{height:10px;background:#eef3f2;border-radius:999px;flex:1;overflow:hidden;position:relative}
.progress-fill{height:100%;border-radius:999px;background:linear-gradient(90deg,var(--accent-green),var(--accent-blue));width:40%}
.progress-num{font-weight:700;color:#16302f;min-width:40px;text-align:right;font-size:13px}
/* highlighted / unlocked style */
.achievement.unlocked{border:2px solid rgba(18,176,122,0.12);box-shadow:0 12px 30px rgba(18,176,122,0.06)}
.achievement.unlocked .ach-icon{background:linear-gradient(180deg, rgba(18,176,122,0.12), rgba(18,176,122,0.06));color:var(--accent-blue)}
/* Redeem rewards */
.rewards-list{display:flex;flex-direction:column;gap:14px;max-width:720px;margin:26px auto 0}
.reward{
display:flex;align-items:center;justify-content:space-between;
gap:12px;background:var(--card);border-radius:12px;padding:14px 16px;
box-shadow:var(--soft-shadow);border:1px solid rgba(10,20,18,0.03)
}
.reward-left{display:flex;gap:12px;align-items:center}
.reward-icon{width:56px;height:56px;border-radius:12px;background:linear-gradient(180deg, rgba(246,166,35,0.12), rgba(246,166,35,0.04));display:flex;align-items:center;justify-content:center;font-size:20px;color:var(--gold)}
.reward-body{display:flex;flex-direction:column}
.reward-title{font-weight:700}
.reward-sub{color:var(--muted);font-size:13px;margin-top:6px;display:flex;align-items:center;gap:8px}
.reward-actions{display:flex;flex-direction:column;align-items:flex-end;gap:8px}
.points-small{font-weight:800;color:var(--gold);font-size:13px}
.btn-redeem{background:var(--gold);color:#fff;padding:8px 14px;border-radius:12px;border:0;font-weight:700;cursor:pointer;box-shadow:0 8px 18px rgba(246,166,35,0.14)}
/* disabled reward */
.reward.disabled{opacity:0.6}
.reward.disabled .btn-redeem{background:#ffda9b;color:#fff;opacity:0.6;cursor:not-allowed}
/* bottom nav */
.bottom-nav{
position:fixed;left:50%;transform:translateX(-50%);bottom:12px;width:96%;max-width:980px;background:rgba(255,255,255,1);border-radius:16px;padding:8px 18px;box-shadow:0 18px 40px rgba(12,30,25,0.06);display:flex;justify-content:space-around;align-items:center;gap:10px;border:1px solid rgba(10,20,18,0.04);
}
.nav-item{display:flex;flex-direction:column;align-items:center;gap:6px;color:var(--muted);font-size:12px;text-decoration:none}
.nav-item.active{background:#e9fff4;padding:8px 12px;border-radius:12px;color:var(--accent-green)}
/* responsiveness */
@media (max-width:720px){
.points-card{max-width:360px}
.achievement,.reward{padding:12px}
.ach-icon{width:48px;height:48px}
.reward-icon{width:48px;height:48px}
.reward-sub{font-size:12px}
}
@media (max-width:420px){
.progress-num{min-width:36px;font-size:12px}
.points-card{padding:18px}
.reward-actions{align-items:flex-end}
.btn-redeem{padding:8px 10px}
}
</style>
</head>
<body>
<header class="hero" role="banner" aria-label="Rewards header">
<div class="container">
<div class="hero-top">
<div style="display:flex;align-items:center;gap:12px;">
<div style="width:36px;height:36px;border-radius:8px;background:rgba(255,255,255,0.14);display:flex;align-items:center;justify-content:center;">🏅</div>
<div>
<h1>Rewards & Points</h1>
<div class="hero-sub">Earn rewards for sustainable choices</div>
</div>
</div>
</div>
<div class="points-card" role="region" aria-label="Total eco points">
<div style="font-size:18px;opacity:0.95">📈</div>
<div class="num" id="ecoPoints">1,247</div>
<div class="label">Total Eco Points</div>
</div>
</div>
</header>
<main>
<div class="container">
<h2 class="section-title">Achievements</h2>
<section class="achievements" id="achievementsList" aria-live="polite">
<!-- JS renders achievements -->
</section>
<h2 class="section-title" style="margin-top:28px">Redeem Rewards</h2>
<section class="rewards-list" id="rewardsList" aria-live="polite">
<!-- JS renders rewards -->
</section>
</div>
</main>
<nav class="bottom-nav" role="navigation" aria-label="Main navigation">
<a href="Index.html" class="nav-item" aria-label="Home">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M3 11.5L12 4l9 7.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 21h14V11" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Home</span>
</a>
<a href="scan.html" class="nav-item" aria-label="Scan">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/><rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/><path d="M21 3v7M3 21v-7" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
<span>Scan</span>
</a>
<a href="history.html" class="nav-item" aria-label="History">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M3 12a9 9 0 1 0 9-9" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 7v6l4 2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>History</span>
</a>
<a href="rewards.html" class="nav-item active" aria-current="page" aria-label="Rewards">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M12 2l2.5 6L20 9l-5 3.8L16 20l-4-2.5L8 20l1-7.2L4 9l5.5-1L12 2z" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Rewards</span>
</a>
</nav>
<script>
const API_URL = 'http://localhost:3000/api';
let _apiOk = null;
async function apiAvailable(){
if (_apiOk !== null) return _apiOk;
try{ const r = await fetch(`${API_URL}/health`, { cache:'no-store' }); _apiOk = r.ok; }
catch(e){ _apiOk = false; }
return _apiOk;
}
// Static reward catalog
const rewards = [
{ id:1, title:"10% Off Organic Store", cost:500, subtitle:"500 points", icon:"🎁", enabled:true },
{ id:2, title:"Free Local Farm Tour", cost:1000, subtitle:"1000 points", icon:"🎟️", enabled:true },
{ id:3, title:"Eco Tote Bag", cost:1500, subtitle:"1500 points", icon:"🛍️", enabled:true }
];
const ecoPointsEl = document.getElementById('ecoPoints');
let ecoPoints = 0;
const OVERRIDE_KEY = 'ecoPointsOverride';
// utilities
function clamp(v,min,max){ return Math.max(min,Math.min(max,v)); }
function percent(curr,tot){ if(tot<=0) return 0; return (curr / tot) * 100; }
function estimateCarbonKg(name){
const n = String(name||'').toLowerCase();
const low = /(apple|banana|lettuce|spinach|oat|almond|plant|vegan|bean|chickpea|pasta)/.test(n);
const base = low ? 0.3 : 1.2;
const jitter = 0.2; // keep stable-ish for rewards display
return Number((base + jitter).toFixed(2));
}
function getCarbon(item){
const c = item && item.carbon;
if (typeof c === 'number' && !Number.isNaN(c)) return c;
if (typeof c === 'string'){
const v = parseFloat(c);
if (!Number.isNaN(v)) return v;
}
// estimate from title/name as fallback
return estimateCarbonKg(item && (item.title || item.name || ''));
}
// Compute achievements from history
const achContainer = document.getElementById('achievementsList');
function buildAchievements(history){
const total = history.length;
const ecoFriendly = history.filter(h => String(h.eco||'').toUpperCase().includes('A')).length;
const healthAGrades = history.filter(h => String(h.nutri||'').toUpperCase()==='A').length;
// ensure we always have a numeric carbon value (coerce or estimate)
const withCarbon = history.map(h => ({...h, carbon: getCarbon(h)}));
const carbonSaved = withCarbon.reduce((s,h)=> s + Math.max(0, 0.7 - (typeof h.carbon === 'number' ? h.carbon : getCarbon(h))), 0);
const perfectWeek = Math.min(7, healthAGrades); // simple proxy
return [
{ id:1, title: 'Eco Warrior', desc:'Scan 50 eco-friendly products', icon:'🏆', current: ecoFriendly, total:50 },
{ id:2, title: 'Health Champion', desc:'Track 30 days in a row', icon:'⭐', current: Math.min(30, total), total:30 },
{ id:3, title: 'Carbon Saver', desc:'Save 10kg CO₂', icon:'🍃', current: Number(carbonSaved.toFixed(2)), total:10 },
{ id:4, title: 'Perfect Week', desc:'All A-grade products for a week', icon:'🎯', current: perfectWeek, total:7 }
];
}
function renderAchievements(achievements){
achContainer.innerHTML = '';
achievements.forEach(a=>{
const el = document.createElement('div');
const p = percent(a.current,a.total);
const isUnlocked = a.current >= a.total;
el.className = 'achievement' + (isUnlocked ? ' unlocked' : '');
el.innerHTML = `
<div class="ach-icon" aria-hidden>${a.icon}</div>
<div class="ach-body">
<div class="ach-title">${escapeHtml(a.title)} ${isUnlocked ? '<span style="display:inline-block;margin-left:8px;padding:4px 8px;background:rgba(18,176,122,0.08);border-radius:10px;color:var(--accent-green);font-weight:700;font-size:12px">Unlocked</span>' : ''}</div>
<div class="ach-desc">${escapeHtml(a.desc)}</div>
<div class="progress-row">
<div class="progress-bg" role="progressbar" aria-valuemin="0" aria-valuemax="${a.total}" aria-valuenow="${a.current}">
<div class="progress-fill" style="width:${clamp(p,0,100)}%"></div>
</div>
<div class="progress-num">${a.current}/${a.total}</div>
</div>
</div>
`;
// click to claim if unlocked
el.addEventListener('click', () => {
if(isUnlocked) {
const bonus = 25;
ecoPoints += bonus;
localStorage.setItem(OVERRIDE_KEY, String(ecoPoints));
ecoPointsEl.textContent = ecoPoints.toLocaleString();
alert(`${a.title} claimed! You earned +${bonus} eco points.`);
} else {
alert(`${a.title}\n\nProgress: ${a.current}/${a.total}\n\nKeep going to unlock this achievement.`);
}
});
achContainer.appendChild(el);
});
}
// render rewards list
const rewardsContainer = document.getElementById('rewardsList');
function renderRewards(){
rewardsContainer.innerHTML = '';
rewards.forEach(r=>{
const enabled = ecoPoints >= r.cost && r.enabled;
const item = document.createElement('div');
item.className = 'reward' + (enabled ? '' : ' disabled');
item.innerHTML = `
<div class="reward-left">
<div class="reward-icon" aria-hidden>${r.icon}</div>
<div class="reward-body">
<div class="reward-title">${escapeHtml(r.title)}</div>
<div class="reward-sub"><span style="display:inline-block;width:18px;height:18px;border-radius:6px;background:rgba(246,166,35,0.06);display:inline-flex;align-items:center;justify-content:center;color:var(--gold);font-size:12px;margin-right:6px">🏷️</span> <span class="points-small">${r.subtitle}</span></div>
</div>
</div>
<div class="reward-actions">
<div class="points-small">${r.cost} pts</div>
<button class="btn-redeem" ${enabled ? '' : 'disabled'}>${enabled ? 'Redeem' : 'Redeem'}</button>
</div>
`;
// redeem click
item.querySelector('.btn-redeem').addEventListener('click', async (e)=>{
e.stopPropagation();
if(!enabled){ alert('Not enough points to redeem this reward.'); return; }
if(confirm(`Redeem "${r.title}" for ${r.cost} points?`)){
try{
if (await apiAvailable()){
const resp = await fetch(`${API_URL}/redeem`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ rewardId: r.id, title: r.title, cost: r.cost })
});
const data = await resp.json();
if (!resp.ok || data.error){
alert(data.error || 'Redeem failed');
return;
}
ecoPoints = data.points;
} else {
ecoPoints -= r.cost;
localStorage.setItem(OVERRIDE_KEY, String(ecoPoints));
}
ecoPointsEl.textContent = ecoPoints.toLocaleString();
alert(`Redeemed: ${r.title}\nCheck your email for voucher details (demo).`);
} finally {
renderRewards();
}
}
});
rewardsContainer.appendChild(item);
});
}
function navClick(e,name){ e.preventDefault(); alert(`Navigate to: ${name} (demo)`); }
// small XSS safe escape
function escapeHtml(s){ return String(s).replace(/[&<>"']/g, m => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m])); }
// load history and compute points/achievements
(async function init(){
let history = [];
try{
if (await apiAvailable()){
const r = await fetch(`${API_URL}/history`, { cache:'no-store' });
history = await r.json();
} else {
history = JSON.parse(localStorage.getItem('historyScans')||'[]');
}
}catch(e){ history = JSON.parse(localStorage.getItem('historyScans')||'[]'); }
// If no scans at all, force zero points and clear override
if (!Array.isArray(history) || history.length === 0) {
ecoPoints = 0;
try { localStorage.removeItem(OVERRIDE_KEY); } catch(_){}
} else {
// load points
try{
if (await apiAvailable()){
const pr = await fetch(`${API_URL}/points`, { cache:'no-store' });
const pdata = await pr.json();
ecoPoints = typeof pdata.points === 'number' ? pdata.points : 0;
} else {
const sumPoints = history.reduce((s,h)=> s + (parseInt(h.points,10)||0), 0);
const override = localStorage.getItem(OVERRIDE_KEY);
ecoPoints = override ? parseInt(override,10) : sumPoints;
}
} catch(e){
const sumPoints = history.reduce((s,h)=> s + (parseInt(h.points,10)||0), 0);
const override = localStorage.getItem(OVERRIDE_KEY);
ecoPoints = override ? parseInt(override,10) : sumPoints;
}
}
ecoPointsEl.textContent = (ecoPoints||0).toLocaleString();
const achievements = buildAchievements(history || []);
renderAchievements(achievements);
renderRewards();
})();
</script>
</body>
</html>