`; }
+const QUOTES = [
+ ['We are what we repeatedly do. Excellence, then, is not an act, but a habit.','Will Durant'],['The journey of a thousand miles begins with a single step.','Lao Tzu'],
+ ['Little by little, one travels far.','J.R.R. Tolkien'],['It does not matter how slowly you go as long as you do not stop.','Confucius'],
+ ['Waste no more time arguing what a good man should be. Be one.','Marcus Aurelius'],['Small deeds done are better than great deeds planned.','Peter Marshall'],
+ ['Begin at once to live.','Seneca'],['What you do every day matters more than what you do once in a while.','Gretchen Rubin'],
+ ['Set your life on fire. Seek those who fan your flames.','Rumi'],['Motivation gets you going, but habit gets you there.','Zig Ziglar'],
+ ['Success is the sum of small efforts, repeated day in and day out.','Robert Collier'],['The secret of getting ahead is getting started.','Mark Twain'],
+ ['Do not wait to strike till the iron is hot; make it hot by striking.','W.B. Yeats'],['Energy and persistence conquer all things.','Benjamin Franklin'],
+ ['Well begun is half done.','Aristotle'],['Act as if what you do makes a difference. It does.','William James'],
+ ['Habit is a cable; we weave a thread of it each day.','Horace Mann'],['First we make our habits, then our habits make us.','John Dryden'],
];
-const AVATARS = ['π₯','π¦','πΊ','π¦ ','π','βοΈ','π','πΈ','β‘','π','π','π'];
+const quote = () => QUOTES[Math.floor(Date.now() / 864e5) % QUOTES.length];
-/* ---------- haptics & fx ---------- */
+/* ---------- haptics, sound, confetti ---------- */
const buzz = (p = 12) => { try { navigator.vibrate && navigator.vibrate(p); } catch(e){} };
-const AC = window.AudioContext && new (window.AudioContext || window.webkitAudioContext)();
-function tick(f = 880) { if (!AC || localStorage.getItem('ember.sound') === '0') return; try { const o = AC.createOscillator(), g = AC.createGain(); o.frequency.value = f; o.type = 'sine'; g.gain.setValueAtTime(.0001, AC.currentTime); g.gain.exponentialRampToValueAtTime(.08, AC.currentTime + .01); g.gain.exponentialRampToValueAtTime(.0001, AC.currentTime + .18); o.connect(g).connect(AC.destination); o.start(); o.stop(AC.currentTime + .2); } catch(e){} }
-const fx = $('#fx'), ctx = fx.getContext('2d'); let parts = [];
-function burst(x, y, color = '#f2c46d', n = 26) {
+let AC = null;
+function tick(f = 880, d = .18) { if (localStorage.getItem('ember.sound') === '0') return; try { AC = AC || new (window.AudioContext || window.webkitAudioContext)(); const o = AC.createOscillator(), g = AC.createGain(); o.frequency.value = f; o.type = 'triangle'; g.gain.setValueAtTime(.0001, AC.currentTime); g.gain.exponentialRampToValueAtTime(.07, AC.currentTime + .01); g.gain.exponentialRampToValueAtTime(.0001, AC.currentTime + d); o.connect(g).connect(AC.destination); o.start(); o.stop(AC.currentTime + d + .02); } catch(e){} }
+const chime = () => { tick(660); setTimeout(() => tick(880), 80); setTimeout(() => tick(1320, .3), 160); };
+const fx = $('#fx'), ctx = fx.getContext('2d'); let parts = [], fxOn = false;
+const CONF = ['#ffd36b','#ff7a2f','#ff2d8a','#8b5cff','#38e1ff','#ffffff'];
+function burst(x, y, color = '#ff7a2f', n = 34, big = false) {
fx.width = innerWidth * devicePixelRatio; fx.height = innerHeight * devicePixelRatio; ctx.setTransform(devicePixelRatio,0,0,devicePixelRatio,0,0);
- for (let i = 0; i < n; i++) { const a = Math.random() * Math.PI * 2, s = 2 + Math.random() * 5; parts.push({x, y, vx: Math.cos(a)*s, vy: Math.sin(a)*s - 2, l: 1, c: Math.random() < .5 ? color : '#ffe9b8', r: 1.5 + Math.random()*2.5}); }
- if (parts.length === n) requestAnimationFrame(step);
+ for (let i = 0; i < n; i++) { const a = Math.random() * Math.PI * 2, s = (big ? 5 : 2.5) + Math.random() * (big ? 9 : 6);
+ parts.push({x, y, vx: Math.cos(a)*s, vy: Math.sin(a)*s - (big ? 6 : 3), l: 1, c: Math.random() < .35 ? color : CONF[i % CONF.length], w: 4 + Math.random()*6, h: 3 + Math.random()*4, r: Math.random()*6, vr: (Math.random() - .5) * .4, k: Math.random() < .4 ? 0 : 1}); }
+ if (!fxOn) { fxOn = true; requestAnimationFrame(step); }
+}
+function step() { ctx.clearRect(0,0,innerWidth,innerHeight); parts = parts.filter(p => p.l > 0 && p.y < innerHeight + 20);
+ for (const p of parts) { p.x += p.vx; p.y += p.vy; p.vy += .22; p.vx *= .985; p.r += p.vr; p.l -= .012; ctx.globalAlpha = Math.min(1, p.l * 1.6); ctx.fillStyle = p.c;
+ if (p.k) { ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(p.r); ctx.fillRect(-p.w/2, -p.h/2, p.w, p.h * Math.abs(Math.cos(p.r * 2))); ctx.restore(); } else { ctx.shadowBlur = 10; ctx.shadowColor = p.c; ctx.beginPath(); ctx.arc(p.x, p.y, p.h/1.6, 0, 7); ctx.fill(); ctx.shadowBlur = 0; } }
+ if (parts.length) requestAnimationFrame(step); else { ctx.clearRect(0,0,innerWidth,innerHeight); fxOn = false; } }
+function confettiRain() { for (let i = 0; i < 6; i++) setTimeout(() => burst(Math.random() * innerWidth, innerHeight * (.15 + Math.random() * .3), '#ffd36b', 40, true), i * 140); }
+function floatText(x, y, t) { const e = document.createElement('div'); e.textContent = t; e.style.cssText = `position:fixed;left:${x}px;top:${y}px;z-index:80;font-weight:900;font-size:18px;pointer-events:none;background:linear-gradient(90deg,#ffd36b,#ff2d8a);-webkit-background-clip:text;color:transparent;transform:translate(-50%,0);transition:all 1.1s cubic-bezier(.2,1,.3,1);filter:drop-shadow(0 0 8px #ff2d8a)`; document.body.appendChild(e); requestAnimationFrame(() => { e.style.transform = 'translate(-50%,-70px) scale(1.3)'; e.style.opacity = '0'; }); setTimeout(() => e.remove(), 1200); }
+function toast(m) { const t = $('#toast'); t.innerHTML = m; t.classList.add('on'); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove('on'), 2600); }
+
+/* ---------- living flame (SVG core + additive particle canvas) ---------- */
+const flameSVG = (on = true, w = 90) => ``;
+const flameScale = s => .62 + .5 * Math.min(1, s / 30);
+function flame(streak, base = 96, on = true) { const w = Math.round(base * (on ? flameScale(streak) : .62)), cw = Math.round(w * 2.2);
+ return `
${on ? `` : ''}
${flameSVG(on, w)}
`; }
+const SPR = ['#fff3c4','#ffb13b','#ff5a2b','#ff2d8a','#8b5cff'].map(c => { const s = document.createElement('canvas'); s.width = s.height = 64; const g = s.getContext('2d'), r = g.createRadialGradient(32,32,0,32,32,32); r.addColorStop(0, c); r.addColorStop(.4, c + '88'); r.addColorStop(1, c + '00'); g.fillStyle = r; g.fillRect(0,0,64,64); return s; });
+let flames = [], flameRAF = 0;
+function mountFlames() { flames = [...$$('.fcv')].map(c => ({c, g: c.getContext('2d'), w: +c.dataset.w * 2, p: []})); if (!flameRAF && flames.length) flameRAF = requestAnimationFrame(flameLoop); }
+function flameLoop() {
+ flames = flames.filter(f => f.c.isConnected);
+ for (const f of flames) { const {g, c, w} = f, W = c.width, H = c.height, bx = W / 2, by = H - w * .3;
+ for (let i = 0; i < 3; i++) f.p.push({x: bx + (Math.random() - .5) * w * .45, y: by - Math.random() * w * .2, vx: (Math.random() - .5) * .6, vy: -(1 + Math.random() * 2.2) * w / 110, l: 1, s: w * (.22 + Math.random() * .2), d: .012 + Math.random() * .014});
+ if (Math.random() < .25) f.p.push({x: bx + (Math.random() - .5) * w * .5, y: by - w * .6, vx: (Math.random() - .5) * 1.4, vy: -(2 + Math.random() * 2.5) * w / 110, l: 1, s: w * .05, d: .008, e: 1});
+ g.clearRect(0, 0, W, H); g.globalCompositeOperation = 'lighter';
+ f.p = f.p.filter(p => p.l > 0);
+ for (const p of f.p) { p.x += p.vx + Math.sin((p.y + performance.now() * .05) * .03) * .4; p.y += p.vy; p.l -= p.d; if (!p.e) p.x += (bx - p.x) * .012;
+ const k = p.e ? 1 : p.l > .75 ? 0 : p.l > .5 ? 1 : p.l > .3 ? 2 : p.l > .15 ? 3 : 4, sz = p.e ? p.s : p.s * (.4 + p.l * .8);
+ g.globalAlpha = Math.min(1, p.l * (p.e ? 1.2 : .55)); g.drawImage(SPR[k], p.x - sz, p.y - sz, sz * 2, sz * 2); }
+ if (f.p.length > 260) f.p.splice(0, f.p.length - 260);
+ }
+ flameRAF = flames.length ? requestAnimationFrame(flameLoop) : 0;
}
-function step() { ctx.clearRect(0,0,innerWidth,innerHeight); parts = parts.filter(p => p.l > 0); for (const p of parts) { p.x += p.vx; p.y += p.vy; p.vy += .18; p.vx *= .98; p.l -= .022; ctx.globalAlpha = Math.max(p.l,0); ctx.fillStyle = p.c; ctx.beginPath(); ctx.arc(p.x,p.y,p.r,0,7); ctx.fill(); } if (parts.length) requestAnimationFrame(step); else ctx.clearRect(0,0,innerWidth,innerHeight); }
-function toast(m) { const t = $('#toast'); t.textContent = m; t.classList.add('on'); clearTimeout(t._t); t._t = setTimeout(() => t.classList.remove('on'), 2600); }
+
+/* ---------- parallax & tilt ---------- */
+let tx = 0, ty = 0;
+function applyTilt() { $$('.tilt').forEach(el => el.style.transform = `perspective(900px) rotateX(${ty * -5}deg) rotateY(${tx * 6}deg)`); ['.o1', '.o2', '.o3'].forEach((s, i) => { const o = $(s); if (o) o.style.translate = `${tx * (20 + i * 14)}px ${ty * (20 + i * 10) - scrollY * (.08 + i * .05)}px`; }); }
+addEventListener('pointermove', e => { if (e.pointerType !== 'mouse') return; tx = e.clientX / innerWidth - .5; ty = e.clientY / innerHeight - .5; requestAnimationFrame(applyTilt); }, {passive: true});
+addEventListener('deviceorientation', e => { if (e.gamma == null) return; tx = Math.max(-1, Math.min(1, e.gamma / 30)) / 2; ty = Math.max(-1, Math.min(1, (e.beta - 45) / 30)) / 2; requestAnimationFrame(applyTilt); }, {passive: true});
+addEventListener('scroll', () => requestAnimationFrame(applyTilt), {passive: true});
/* ---------- API ---------- */
async function api(path, body, method) {
const r = await fetch('/api' + path, {method: method || (body ? 'POST' : 'GET'), headers: {'content-type': 'application/json', ...(TOK ? {authorization: 'Bearer ' + TOK} : {})}, body: body ? JSON.stringify(body) : undefined});
let j = null; try { j = await r.json(); } catch(e){}
- if (r.status === 401 && TOK && !path.startsWith('/login')) { logout(true); }
+ if (r.status === 401 && TOK && !path.startsWith('/login')) logout(true);
if (!r.ok) throw new Error((j && (typeof j.detail === 'string' ? j.detail : 'Please check your input')) || 'Network error');
return j;
}
function setMe(m) { if (!m || !m.username) return; ME = m; localStorage.setItem('ember.me', JSON.stringify(m)); badge(); }
function logout(silent) { TOK = null; ME = null; localStorage.removeItem('ember.tok'); localStorage.removeItem('ember.me'); if (!silent) toast('Signed out'); location.hash = '#/welcome'; }
-// offline queue for check-ins
let Q = JSON.parse(localStorage.getItem('ember.q') || '[]');
async function flush() { while (Q.length && navigator.onLine) { const op = Q[0]; try { setMe(await api(op.p, op.b)); Q.shift(); localStorage.setItem('ember.q', JSON.stringify(Q)); } catch(e) { break; } } }
addEventListener('online', flush);
-/* ---------- streak maths ---------- */
+/* ---------- streaks, XP, badges ---------- */
function streakOf(h, today = new Date()) {
const s = new Set(h.days || []);
if (h.kind === 'weekly') {
const wk = d => { const x = new Date(d); x.setDate(x.getDate() - ((x.getDay() + 6) % 7)); return iso(x); };
const cnt = {}; for (const d of s) { const k = wk(new Date(d + 'T12:00')); cnt[k] = (cnt[k] || 0) + 1; }
- let cur = new Date(today); let c = 0; if ((cnt[wk(cur)] || 0) < h.n) cur = addD(cur, -7);
+ let cur = new Date(today), c = 0; if ((cnt[wk(cur)] || 0) < h.n) cur = addD(cur, -7);
while ((cnt[wk(cur)] || 0) >= h.n) { c++; cur = addD(cur, -7); } return c;
}
let cur = new Date(today); if (!s.has(iso(cur))) cur = addD(cur, -1);
@@ -65,54 +151,79 @@ const weekDone = h => { const now = new Date(), mon = addD(now, -((now.getDay()
const habits = () => (ME && ME.habits) || [];
const topStreak = () => Math.max(0, ...habits().map(h => streakOf(h)));
const unit = h => h.kind === 'weekly' ? 'week' : 'day';
+function perfectDays() { const d = habits().filter(h => h.kind !== 'weekly'); if (!d.length) return 0; const cnt = {}; d.forEach(h => (h.days||[]).forEach(x => cnt[x] = (cnt[x] || 0) + 1)); return Object.values(cnt).filter(v => v >= d.length).length; }
+const TITLES = ['Spark','Kindle','Flicker','Flame','Blaze','Wildfire','Inferno','Phoenix','Solar','Supernova'];
+function xpInfo() { const hs = habits(), total = hs.reduce((a, h) => a + (h.days||[]).length, 0);
+ const xp = total * 10 + hs.reduce((a, h) => a + bestEver(h), 0) * 5 + perfectDays() * 15 + ((ME && ME.friends) || []).length * 20;
+ let lv = 1, need = 100, acc = 0; while (xp >= acc + need) { acc += need; lv++; need = 100 + (lv - 1) * 60; }
+ return {xp, lv, into: xp - acc, need, title: TITLES[Math.min(TITLES.length - 1, Math.floor((lv - 1) / 2))], total}; }
+const BADGES = [
+ ['first','First Spark','Your first check-in',['#ffd36b','#ff6a2b'],'spark', s => s.total >= 1],
+ ['s3','Kindled','3-day streak',['#ff9b4a','#ff2d8a'],'flame', s => s.best >= 3],
+ ['s7','Week Warrior','7-day streak',['#ff6a2b','#ff2d8a'],'bolt', s => s.best >= 7],
+ ['s14','Fortnight','14-day streak',['#ff2d8a','#8b5cff'],'star', s => s.best >= 14],
+ ['s30','Monthly Flame','30-day streak',['#8b5cff','#38e1ff'],'crown', s => s.best >= 30],
+ ['s66','Habit Formed','66-day streak',['#38e1ff','#2fe0a0'],'medal', s => s.best >= 66],
+ ['c50','Half Century','50 check-ins',['#ffd36b','#c45cff'],'target', s => s.total >= 50],
+ ['c100','Centurion','100 check-ins',['#ff6a2b','#8b5cff'],'trophy', s => s.total >= 100],
+ ['perfect','Perfect Day','Every daily habit, one day',['#2fe0a0','#38e1ff'],'check', s => s.perfect >= 1],
+ ['p7','Flawless Seven','7 perfect days',['#38e1ff','#8b5cff'],'shield', s => s.perfect >= 7],
+ ['col','Collector','5 active habits',['#c45cff','#ff2d8a'],'palette', s => s.habits >= 5],
+ ['friend','Better Together','Add a friend',['#ff2d8a','#ffd36b'],'heart', s => s.friends >= 1],
+ ['circle','Inner Circle','5 friends',['#ff7a2f','#c2185b'],'users', s => s.friends >= 5],
+ ['chal','Challenger','Join a group challenge',['#ffd36b','#ff2d8a'],'rocket', s => s.chal >= 1],
+ ['lv5','Blaze','Reach level 5',['#ff6a2b','#ffd36b'],'flame', s => s.lv >= 5],
+];
+function badgeStats() { const hs = habits(), x = xpInfo(); return {total: x.total, best: Math.max(0, ...hs.map(bestEver)), perfect: perfectDays(), habits: hs.length, friends: (ME.friends || []).length, chal: Number(localStorage.getItem('ember.chal') || 0), lv: x.lv}; }
+const earned = () => { const s = badgeStats(); return BADGES.filter(b => b[5](s)).map(b => b[0]); };
+const medal = (b, lock) => `
`,
- t: 'Small rituals. Lasting fire.', p: 'Ember turns the things you care about β training, reading, prayer, stillness β into a streak worth protecting.'},
- {art: () => `
`,
- t: 'See every day you showed up.', p: 'A living heatmap, elegant stats and a flame that grows with you. Miss a day? Begin again β gently.'},
- {art: () => `
${['π¦','π','π₯','β‘'].map((a, i) => `
${a}
`).join('')}
`,
- t: 'Better together.', p: 'Invite friends with a link, join group challenges, climb the leaderboard and send a cheer when it matters.'},
+ {art: () => `
`,
+ t: 'Small rituals. Lasting fire.', p: 'Ember turns the things you care about (training, reading, prayer, stillness) into a streak worth protecting.'},
+ {art: () => `
`,
+ t: 'Better together.', p: 'Invite friends with a link, join group challenges, climb the podium and send a cheer when it matters.'},
];
routes.welcome = () => {
- let i = 0; const inv = localStorage.getItem('ember.inv');
+ let i = 0;
const draw = () => { const s = SLIDES[i]; app.innerHTML = `
-
Ember
${i < 2 ? '' : ''}
+
Ember
${i < 2 ? '' : ''}
${s.art()}
${s.t}
${s.p}
- ${inv && invInfo ? `
${esc(invInfo.avatar)}
${esc(invInfo.display)} invited you
Join and you'll be friends automatically
` : ''}
+ ${invInfo ? `
${av(invInfo)}
${esc(invInfo.display)} invited you
Join and you'll be friends automatically
` : ''}
${SLIDES.map((_, j) => ``).join('')}
`;
$('#next').onclick = () => { buzz(); if (i < 2) { i++; draw(); } else location.hash = '#/auth/signup'; };
const sk = $('#skip'); if (sk) sk.onclick = () => { i = 2; draw(); };
let x0 = null; $('#sl').ontouchstart = e => x0 = e.touches[0].clientX; $('#sl').ontouchend = e => { const dx = e.changedTouches[0].clientX - x0; if (dx < -40 && i < 2) { i++; draw(); } else if (dx > 40 && i > 0) { i--; draw(); } };
+ after();
};
draw();
};
@@ -120,8 +231,8 @@ let invInfo = null;
routes.auth = mode => {
const su = mode !== 'login';
app.innerHTML = `
${backBtn('#/welcome')}
-
${flame(true,'width:54px;height:66px')}
${su ? 'Light your first ember.' : 'Welcome back.'}
-
${su ? 'Free forever. No email needed β just a username your friends can find.' : 'Sign in to keep your streaks burning.'}
+
${flame(8, 60)}
${su ? 'Light your first ember.' : 'Welcome back.'}
+
${su ? 'Free forever. No email needed, just a username your friends can find.' : 'Sign in to keep your streaks burning.'}