-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
538 lines (499 loc) · 24.1 KB
/
script.js
File metadata and controls
538 lines (499 loc) · 24.1 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
'use strict';
// Smooth scroll for anchor links and arrow button (respects reduced motion)
(function(){
const prefersReduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function smoothScrollTo(target) {
if (!target) return;
const el = (typeof target === 'string') ? document.querySelector(target) : target;
if (!el) return;
el.scrollIntoView({ behavior: prefersReduced ? 'auto' : 'smooth', block: 'start' });
}
document.querySelectorAll('a[href^="#"]').forEach(a => {
a.addEventListener('click', e => {
const href = a.getAttribute('href');
if (href && href.length > 1) {
e.preventDefault();
smoothScrollTo(href);
}
}, { passive: false });
});
document.querySelectorAll('.down-arrow').forEach(btn => {
btn.addEventListener('click', () => {
const target = btn.getAttribute('data-scroll-target') || '#mission';
smoothScrollTo(target);
});
});
})();
// Reveal-on-scroll with IntersectionObserver (fallback: show all)
(function(){
const items = document.querySelectorAll('.reveal');
if (!('IntersectionObserver' in window)) {
items.forEach(i => i.classList.add('is-visible'));
return;
}
const obs = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('is-visible');
observer.unobserve(entry.target);
}
});
}, { threshold: 0.15, rootMargin: '0px 0px -40px 0px' });
items.forEach(i => obs.observe(i));
})();
// Glassy navbar: shrink on scroll, hide on scroll-down, show on scroll-up
(function(){
const header = document.getElementById('site-header');
const toggle = document.querySelector('.nav-toggle');
const menu = document.getElementById('nav-menu');
if (!header) return;
let lastY = window.scrollY || 0;
const onScroll = () => {
const y = window.scrollY || 0;
if (y > 20) header.classList.add('scrolled'); else header.classList.remove('scrolled');
if (y > lastY + 10 && y > 80) header.classList.add('hide');
if (y < lastY - 10) header.classList.remove('hide');
lastY = y;
};
window.addEventListener('scroll', onScroll, { passive: true });
if (toggle && menu) {
function setOpen(open){
header.classList.toggle('open', open);
toggle.setAttribute('aria-expanded', String(open));
document.body.style.overflow = open ? 'hidden' : '';
}
toggle.addEventListener('click', () => {
const willOpen = !header.classList.contains('open');
setOpen(willOpen);
});
// Close on link click (for mobile)
document.querySelectorAll('.nav-menu a').forEach(a => a.addEventListener('click', () => {
setOpen(false);
}));
// Close on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') setOpen(false);
});
// Close on overlay click
header.addEventListener('click', (e) => {
if (header.classList.contains('open') && e.target === header) setOpen(false);
});
}
})();
// Internationalization (EN/TR) with safe textContent updates
(function(){
const allowed = ['en','tr'];
const langBtns = document.querySelectorAll('.lang-btn');
const t = {
en: {
brand: 'Cosotech',
'nav.home': 'Home',
'nav.about': 'About',
'nav.team': 'Team',
'nav.missions': 'Our Missions',
'nav.contact': 'Contact',
'hero.title': 'Cosotech Reaching for the Stars',
'hero.lead': "We are five passionate high school students dedicated to aerospace engineering, united by our mission to innovate, create, and push the boundaries of what's possible through the Teknofest Model Rocket Competition.",
'hero.scroll': 'Scroll to explore',
'mission.title': 'Our Mission',
'mission.p1': 'At Cosotech, we believe that the future of space exploration begins with young minds 敢于梦想和创新. Our team is dedicated to designing, building, and launching model rockets that push the boundaries of what\'s possible while learning the fundamentals of aerospace engineering.',
'mission.p2': "Through the prestigious Teknofest Model Rocket Competition, we showcase our technical skills, creativity, and teamwork, inspiring others to pursue careers in STEM fields and contribute to Turkey\'s growing aerospace sector.",
'team.title': 'Meet Our Team',
'team.subtitle': 'Five passionate students on a mission to the stars',
'role.leader': 'Team Leader',
'role.propulsion': 'Propulsion Engineer',
'role.aero': 'Aerodynamics Specialist',
'role.structural': 'Structural Engineer',
'role.electronics': 'Electronics Engineer',
'competition.title': 'Teknofest Model Rocket Competition',
'competition.p1': "Teknofest is Turkey\'s premier aerospace and technology festival, bringing together the brightest young minds to compete in various categories including model rocketry. Our team is proud to participate in this prestigious competition, where we test our engineering skills against the best teams from across Turkey and beyond.",
'stats.members': 'Team Members',
'stats.altitude': 'Target Altitude',
'stats.mission': 'Mission',
'btn.explore': 'Explore Our Missions',
'cta.title': 'Ready to Launch',
'cta.text': 'Follow our journey as we reach for the stars',
'cta.btn': 'Get In Touch',
'stars.skip': 'Skip animation',
'contact.title': 'Get in Touch',
'contact.subtitle': "We'd love to hear from you. Reach out with questions, partnerships, or encouragement.",
'contact.info': 'Contact Information',
'contact.cards.emailTitle': 'Email',
'contact.cards.emailText': 'For general inquiries and media.',
'contact.cards.socialTitle': 'Social',
'contact.cards.socialText': 'Follow our journey on social media.',
'contact.cards.locationTitle': 'Location',
'contact.cards.locationText': 'Turkey • Remote collaboration',
'contact.form.title': 'Send us a message',
'contact.form.nameLabel': 'Name',
'contact.form.emailLabel': 'Email',
'contact.form.msgLabel': 'Message',
'contact.form.submit': 'Send',
'contact.form.emailInvalid': 'Please enter a valid email address.',
'contact.form.opening': 'Opening your email app...',
'team.page.title': 'Meet Our Team',
'team.page.subtitle': 'Five passionate students on a mission to the stars.',
'team.page.members': 'Team Members',
'about.title': 'About Cosotech',
'about.subtitle': 'A student team united by curiosity, engineering, and the spirit of flight.',
'about.story.title': 'Our Story',
'about.story.p1': 'We started Cosotech with a shared dream: to learn by building, test by launching, and grow by collaborating. Teknofest’s Model Rocket Competition became our stage to apply theory in the real world.',
'about.story.p2': 'From CAD and aerodynamics to propulsion and electronics, our workflow is hands-on and iterative. We document, test, and improve continuously—celebrating both successes and lessons.',
'about.values.title': 'Values',
'about.values.v1t': 'Innovation',
'about.values.v1d': 'We design boldly and iterate responsibly.',
'about.values.v2t': 'Collaboration',
'about.values.v2d': 'We learn fastest when we learn together.',
'about.values.v3t': 'Safety',
'about.values.v3d': 'We put safety first in design, testing, and launches.',
'missions.title': 'Our Missions',
'missions.subtitle': 'From design to launch — pushing boundaries with every flight.',
'missions.current': 'Current Mission',
'missions.m1.title': 'Model Rocket — Target 1000m+',
'missions.m1.desc': 'A lightweight, stable rocket optimized for altitude, with reliable recovery and telemetry.',
'missions.cta.title': 'Follow the Journey',
'missions.cta.text': 'Stay updated as we build, test, and launch. Your feedback helps us improve.',
'missions.cta.btn': 'Contact Us'
},
tr: {
brand: 'Cosotech',
'nav.home': 'Ana Sayfa',
'nav.about': 'Hakkımızda',
'nav.team': 'Ekip',
'nav.missions': 'Misyonlarımız',
'nav.contact': 'İletişim',
'hero.title': 'Cosotech Yıldızlara Ulaşıyor',
'hero.lead': 'Biz, Teknofest Model Roket Yarışması aracılığıyla yenilik üretmeye, tasarlamaya ve mümkün olanın sınırlarını zorlamaya adanmış beş tutkulu lise öğrencisiyiz.',
'hero.scroll': 'Keşfetmek için kaydırın',
'mission.title': 'Misyonumuz',
'mission.p1': 'Cosotech\'te, uzay keşfinin geleceğinin genç zihinlerle başladığına inanıyoruz 敢于梦想和创新. Ekibimiz, havacılık ve uzay mühendisliğinin temellerini öğrenirken mümkün olanın sınırlarını zorlayan model roketler tasarlamaya, inşa etmeye ve fırlatmaya kendini adamıştır.',
'mission.p2': 'Prestijli Teknofest Model Roket Yarışması ile teknik becerilerimizi, yaratıcılığımızı ve takım çalışmamızı sergileyerek, STEM alanlarına ilgiyi artırmayı ve Türkiye\'nin büyüyen havacılık ve uzay ekosistemine katkı sunmayı amaçlıyoruz.',
'team.title': 'Ekibimizle Tanışın',
'team.subtitle': 'Yıldızlara giden yolda beş tutkulu öğrenci',
'role.leader': 'Takım Lideri',
'role.propulsion': 'İtki Mühendisi',
'role.aero': 'Aerodinamik Uzmanı',
'role.structural': 'Yapısal Mühendis',
'role.electronics': 'Elektronik Mühendisi',
'competition.title': 'Teknofest Model Roket Yarışması',
'competition.p1': 'Teknofest, Türkiye\'nin önde gelen havacılık ve teknoloji festivalidir; model roketçilik de dahil olmak üzere pek çok kategoride en parlak gençleri bir araya getirir. Ekibimiz, Türkiye ve ötesindeki en iyi takımlarla mühendislik yeteneklerimizi sınadığımız bu prestijli yarışmada yer almaktan gurur duyuyor.',
'stats.members': 'Takım Üyesi',
'stats.altitude': 'Hedef İrtifa',
'stats.mission': 'Misyon',
'btn.explore': 'Misyonlarımızı Keşfedin',
'cta.title': 'Fırlatmaya Hazır',
'cta.text': 'Yıldızlara uzanan yolculuğumuzu takip edin',
'cta.btn': 'İletişime Geçin',
'stars.skip': 'Animasyonu geç',
'contact.title': 'İletişime Geçin',
'contact.subtitle': 'Sizden haber almak isteriz. Sorular, iş birlikleri veya destek için bize ulaşın.',
'contact.info': 'İletişim Bilgileri',
'contact.cards.emailTitle': 'E-posta',
'contact.cards.emailText': 'Genel sorular ve medya için.',
'contact.cards.socialTitle': 'Sosyal',
'contact.cards.socialText': 'Yolculuğumuzu sosyal medyada takip edin.',
'contact.cards.locationTitle': 'Konum',
'contact.cards.locationText': 'Türkiye • Uzaktan çalışma',
'contact.form.title': 'Bize mesaj gönderin',
'contact.form.nameLabel': 'Ad Soyad',
'contact.form.emailLabel': 'E-posta',
'contact.form.msgLabel': 'Mesaj',
'contact.form.submit': 'Gönder',
'contact.form.emailInvalid': 'Geçerli bir e‑posta adresi girin.',
'contact.form.opening': 'E-posta uygulamanız açılıyor...',
'team.page.title': 'Ekibimizle Tanışın',
'team.page.subtitle': 'Yıldızlara giden yolda beş tutkulu öğrenci',
'team.page.members': 'Takım Üyeleri',
'about.title': 'Cosotech Hakkında',
'about.subtitle': 'Merak, mühendislik ve uçuş ruhuyla birleşen bir öğrenci takımı.',
'about.story.title': 'Hikayemiz',
'about.story.p1': 'Cosotech\'i ortak bir hayalle kurduk: yaparak öğrenmek, fırlatarak sınamak ve birlikte çalışarak büyümek. Teknofest Model Roket Yarışması, teoriyi gerçeğe dönüştürdüğümüz sahnemiz oldu.',
'about.story.p2': 'CAD ve aerodinamikten itkiye ve elektroniğe kadar iş akışımız uygulamalı ve yinelemelidir. Başarıları ve çıkarımları sürekli belgeliyor, test ediyor ve geliştiriyoruz.',
'about.values.title': 'Değerler',
'about.values.v1t': 'İnovasyon',
'about.values.v1d': 'Cesur tasarlarız ve sorumlu şekilde iterasyon yaparız.',
'about.values.v2t': 'İş Birliği',
'about.values.v2d': 'En hızlı birlikte öğrenirken öğreniriz.',
'about.values.v3t': 'Güvenlik',
'about.values.v3d': 'Tasarımda, testte ve fırlatmalarda güvenliği önceleyiz.',
'missions.title': 'Misyonlarımız',
'missions.subtitle': 'Tasarım aşamasından fırlatmaya — her uçuşla sınırları zorluyoruz.',
'missions.current': 'Güncel Misyon',
'missions.m1.title': 'Model Roket — Hedef 1000m+',
'missions.m1.desc': 'Yüksek irtifa için optimize edilmiş, kararlı, güvenilir kurtarma ve telemetriye sahip hafif bir roket.',
'missions.cta.title': 'Yolculuğu Takip Edin',
'missions.cta.text': 'Geliştirirken, test ederken ve fırlatırken güncel kalın. Geri bildirimleriniz bize güç verir.',
'missions.cta.btn': 'Bize Ulaşın'
}
};
function applyLanguage(lang){
const safeLang = allowed.includes(lang) ? lang : 'en';
document.documentElement.setAttribute('lang', safeLang);
try {
localStorage.setItem('lang', safeLang);
} catch(e) {
// localStorage might be disabled or full
console.warn('Could not save language preference');
}
// Update pressed state
langBtns.forEach(btn => btn.setAttribute('aria-pressed', String(btn.dataset.lang === safeLang)));
// Apply translations
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
const val = key ? t[safeLang][key] : null;
if (typeof val === 'string') el.textContent = val;
});
}
// Expose a read-only getter for other modules (e.g., form) to retrieve translations safely
const i18nGet = function(key){
try {
const lang = document.documentElement.getAttribute('lang') || 'en';
const dict = (t && t[lang]) ? t[lang] : t.en;
return (dict && typeof dict[key] === 'string') ? dict[key] : '';
} catch { return ''; }
};
// Make it read-only and non-configurable
Object.defineProperty(window, '__i18nGet', {
value: i18nGet,
writable: false,
configurable: false,
enumerable: false
});
let saved = null;
try {
saved = localStorage.getItem('lang');
} catch(e) {
// localStorage might be disabled
}
const initial = allowed.includes(saved) ? saved : ((navigator.language || '').toLowerCase().startsWith('tr') ? 'tr' : 'en');
applyLanguage(initial);
langBtns.forEach(btn => btn.addEventListener('click', () => {
const lang = btn.dataset.lang;
if (lang && allowed.includes(lang)) applyLanguage(lang);
}));
})();
// First-visit fullscreen starfield (respects reduced motion, can be skipped)
(function(){
const canvas = document.getElementById('stars-canvas');
if (!canvas) return;
const skipBtn = document.querySelector('.stars-skip');
const prefersReduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (prefersReduced) { canvas.remove(); if (skipBtn) skipBtn.remove(); return; }
const page = (document.body && document.body.dataset && document.body.dataset.page) || '';
const alwaysPlay = page === 'home';
let played = false;
try {
played = sessionStorage.getItem('starsPlayed') === '1';
} catch(e) {
// sessionStorage might be disabled
}
if (!alwaysPlay && played) { canvas.remove(); if (skipBtn) skipBtn.remove(); return; }
const ctx = canvas.getContext('2d');
let w=0, h=0, dpr=1, rafId, running = true, started = false;
function resize(){
dpr = Math.max(1, Math.min(2, window.devicePixelRatio || 1));
w = Math.max(1, Math.floor((window.innerWidth || 1) * dpr));
h = Math.max(1, Math.floor((window.innerHeight || 1) * dpr));
canvas.width = w; canvas.height = h;
ctx.setTransform(1,0,0,1,0,0); // draw in device pixels then scale coords
}
window.addEventListener('resize', resize, { passive: true });
resize();
// Pre-rendered star sprites with color variation
const sprites = [];
const colors = [
{r:255,g:255,b:255,a:1}, // white
{r:200,g:220,b:255,a:0.95}, // blue-white
{r:255,g:240,b:220,a:0.92}, // warm white
{r:180,g:200,b:255,a:0.9}, // blue
{r:255,g:230,b:180,a:0.88} // yellow-white
];
for (let c of colors){
const sp = document.createElement('canvas'); sp.width = sp.height = 32;
const sc = sp.getContext('2d');
const g = sc.createRadialGradient(16,16,0,16,16,16);
g.addColorStop(0, `rgba(${c.r},${c.g},${c.b},${c.a})`);
g.addColorStop(0.35, `rgba(${Math.floor(c.r*0.9)},${Math.floor(c.g*0.9)},${Math.floor(c.b*0.9)},${c.a*0.6})`);
g.addColorStop(1, 'rgba(0,0,0,0)');
sc.fillStyle = g; sc.beginPath(); sc.arc(16,16,16,0,Math.PI*2); sc.fill();
sprites.push(sp);
}
// Layers with depth
const area = (window.innerWidth||800)*(window.innerHeight||600);
const TWINKLES = Math.max(30, Math.min(280, Math.round(area/11000)));
const FIELDS = Math.max(40, Math.min(180, Math.round(area/22000)));
const DISTANT = Math.max(30, Math.min(140, Math.round(area/28000)));
const METEOR_RATE = Math.max(600, Math.min(1400, 1200 - Math.round(area/12000)));
const twinkles = []; // {x,y,size,phase,speed,alpha,sprite}
const field = []; // {x,y,dx,dy,size,depth}
const distant = []; // {x,y,size,alpha} static deep background
const meteors = []; // {x,y,dx,dy,len,life,ttl,colorIdx}
const rnd = (a,b)=>a+Math.random()*(b-a);
const pickSprite = ()=> sprites[Math.floor(Math.random()*sprites.length)];
for (let i=0;i<DISTANT;i++){
distant.push({x:Math.random()*w, y:Math.random()*h, size:rnd(0.4,1.0), alpha:rnd(0.15,0.35)});
}
for (let i=0;i<TWINKLES;i++){
twinkles.push({
x: Math.random()*w, y: Math.random()*h,
size: rnd(0.8, 2.2), phase: Math.random()*Math.PI*2,
speed: rnd(0.006, 0.024), alpha: rnd(0.4, 1.0),
sprite: pickSprite()
});
}
for (let i=0;i<FIELDS;i++){
const sp = rnd(0.03, 0.16); const depth = rnd(0.3,1.0);
field.push({
x: Math.random()*w, y: Math.random()*h,
dx: sp * depth * (Math.random()<0.5?1:-1),
dy: sp * depth * (Math.random()<0.5?0.5:0.25),
size: rnd(0.9, 2.0), depth
});
}
let lastMeteorTime = 0;
function maybeSpawnMeteor(t){
if (t - lastMeteorTime < METEOR_RATE) return;
lastMeteorTime = t;
const fromTop = Math.random() < 0.65;
const startX = fromTop ? Math.random()*w*0.7 : -80;
const startY = fromTop ? -30 : Math.random()*h*0.35;
const ang = rnd(Math.PI*0.6, Math.PI*0.95);
const speed = rnd(4.5, 8.5);
meteors.push({ x:startX, y:startY, dx: Math.cos(ang)*speed, dy: Math.sin(ang)*speed, len: rnd(80, 180), life: 1, ttl: rnd(900, 1600), colorIdx: Math.floor(Math.random()*3) });
if (meteors.length>6) meteors.shift();
}
function drawBackground(){
const g = ctx.createLinearGradient(0,0,0,h);
g.addColorStop(0, '#0d1220');
g.addColorStop(0.5, '#0b0f1a');
g.addColorStop(1, '#09090f');
ctx.fillStyle = g; ctx.fillRect(0,0,w,h);
}
function drawDistant(){
ctx.fillStyle = 'rgba(255,255,255,0.6)';
for (let i=0;i<distant.length;i++){
const d = distant[i];
ctx.globalAlpha = d.alpha;
ctx.beginPath(); ctx.arc(d.x, d.y, d.size, 0, Math.PI*2); ctx.fill();
}
ctx.globalAlpha = 1;
}
function drawTwinkles(dt){
for (let i=0;i<twinkles.length;i++){
const s = twinkles[i];
s.phase += s.speed*dt;
const tw = 0.65 + 0.35*Math.sin(s.phase);
ctx.globalAlpha = Math.max(0.1, Math.min(1, s.alpha*tw));
const size = s.size*9;
ctx.drawImage(s.sprite, s.x-size, s.y-size, size*2, size*2);
}
ctx.globalAlpha = 1;
}
function drawField(){
for (let i=0;i<field.length;i++){
const f = field[i];
f.x += f.dx; f.y += f.dy;
if (f.x < -10) f.x = w+10; if (f.x > w+10) f.x = -10;
if (f.y < -10) f.y = h+10; if (f.y > h+10) f.y = -10;
ctx.globalAlpha = 0.7 + f.depth*0.25;
ctx.fillStyle = 'rgba(255,255,255,0.9)';
ctx.beginPath(); ctx.arc(f.x, f.y, f.size, 0, Math.PI*2); ctx.fill();
}
ctx.globalAlpha = 1;
}
function drawMeteors(dt){
ctx.globalCompositeOperation = 'lighter';
const meteorColors = [
['rgba(100,180,255,0)','rgba(200,230,255,0.95)'],
['rgba(80,200,255,0)','rgba(255,255,255,0.98)'],
['rgba(120,150,255,0)','rgba(180,210,255,0.92)']
];
for (let i=0;i<meteors.length;i++){
const m = meteors[i];
m.x += m.dx; m.y += m.dy; m.ttl -= dt; m.life = Math.max(0, m.ttl/1400);
const trailFactor = 0.18;
const trailX = m.x - m.dx*m.len*trailFactor, trailY = m.y - m.dy*m.len*trailFactor;
const pal = meteorColors[m.colorIdx%3];
const grd = ctx.createLinearGradient(trailX, trailY, m.x, m.y);
grd.addColorStop(0, pal[0]); grd.addColorStop(0.7, pal[1]); grd.addColorStop(1, pal[1]);
ctx.strokeStyle = grd; ctx.lineWidth = 2.5; ctx.lineCap = 'round';
ctx.beginPath(); ctx.moveTo(trailX, trailY); ctx.lineTo(m.x, m.y); ctx.stroke();
// Head glow
const headGrad = ctx.createRadialGradient(m.x,m.y,0,m.x,m.y,4);
headGrad.addColorStop(0, 'rgba(255,255,255,1)');
headGrad.addColorStop(1, 'rgba(200,230,255,0)');
ctx.fillStyle = headGrad; ctx.beginPath(); ctx.arc(m.x, m.y, 4, 0, Math.PI*2); ctx.fill();
}
for (let i=meteors.length-1;i>=0;i--){
const m = meteors[i];
if (m.ttl<=0 || m.x> w+200 || m.y> h+200) meteors.splice(i,1);
}
ctx.globalCompositeOperation = 'source-over';
}
let last = performance.now();
function step(now){
if (!running) return;
const dt = Math.min(32, now - last); last = now; if (!started) started = true;
drawBackground();
drawDistant();
drawField();
drawTwinkles(dt);
maybeSpawnMeteor(now);
drawMeteors(dt);
rafId = requestAnimationFrame(step);
}
function end(){
if (!running) return;
running = false;
try {
sessionStorage.setItem('starsPlayed','1');
} catch(e) {
// sessionStorage might be disabled
}
if (skipBtn) skipBtn.hidden = true;
// Fade out canvas for a smooth transition
canvas.style.transition = 'opacity 400ms ease';
canvas.style.opacity = '0';
const cleanup = () => { if (rafId) cancelAnimationFrame(rafId); canvas.removeEventListener('transitionend', cleanup); canvas.remove(); };
canvas.addEventListener('transitionend', cleanup);
// Safety cleanup
setTimeout(cleanup, 700);
}
if (skipBtn) { skipBtn.hidden = false; skipBtn.addEventListener('click', end); }
requestAnimationFrame((t)=>{ last = t; step(t); });
setTimeout(end, alwaysPlay ? 7000 : 6000);
})();
// Contact form: validate safely and open mailto link
(function(){
const form = document.getElementById('contact-form');
if (!form) return;
const status = document.getElementById('form-status');
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
const MAX_NAME_LENGTH = 80;
const MAX_MESSAGE_LENGTH = 1000;
function setStatus(msg){ if (status) status.textContent = msg || ''; }
function clearStatus(){ setStatus(''); }
function sanitizeText(text) {
return text.replace(/[<>]/g, '').trim();
}
form.addEventListener('submit', (e) => {
e.preventDefault();
if (!form.checkValidity()) { form.reportValidity(); return; }
let name = (form.elements['name']?.value || '').trim();
let email = (form.elements['email']?.value || '').trim();
let message = (form.elements['message']?.value || '').trim();
// Sanitize and validate
name = sanitizeText(name).substring(0, MAX_NAME_LENGTH);
email = sanitizeText(email);
message = sanitizeText(message).substring(0, MAX_MESSAGE_LENGTH);
if (!emailRe.test(email)) { setStatus(window.__i18nGet('contact.form.emailInvalid') || 'Invalid email'); return; }
if (name.length < 2 || message.length < 10) { setStatus('Please provide valid name and message.'); return; }
const subject = `Cosotech contact from ${name || 'visitor'}`;
const body = `Name: ${name}\nEmail: ${email}\n\n${message}`;
const href = `mailto:contact@cosotech.team?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
setStatus(window.__i18nGet('contact.form.opening') || 'Opening your email app...');
// Use location.href to avoid popup blockers (no window.open)
window.location.href = href;
}, { passive: false });
form.addEventListener('input', clearStatus);
})();