import{daily,hash,importance,shiftDay,safeUrl}from'./domain.mjs'; const lang=document.documentElement.lang==='en'?'en':'fr',t=(fr,en)=>lang==='fr'?fr:en,$=s=>document.querySelector(s),all=s=>[...document.querySelectorAll(s)],page=document.body.dataset.page; const storage={get(k,f){try{return JSON.parse(localStorage.getItem('touda.'+k))??f}catch{return f}},set(k,v){try{localStorage.setItem('touda.'+k,JSON.stringify(v))}catch{toast(t('Stockage du navigateur indisponible.','Browser storage unavailable.'))}}}; let meta={themes:[]},preferences=storage.get('interests',[]),favorites=storage.get('favorites',[]),seen=storage.get('seen',[]),events=[]; const path=(name,params={})=>{const u=new URL(name,location.href);u.search='';u.searchParams.set('lang',lang);for(const[k,v]of Object.entries(params))u.searchParams.set(k,v);return u.href},dateKey=(d=new Date())=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; function el(tag,text,cls){const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n}function toast(s){const n=$('#toast');n.textContent=s;n.classList.add('visible');setTimeout(()=>n.classList.remove('visible'),3500)} async function api(params){const r=await fetch(path('api.php',params));if(!r.ok)throw Error('catalog');return r.json()} const themeLabel=id=>{const x=meta.themes.find(t=>t.id===id);return x?`${x.emoji} ${x[lang]}`:id}; function toggleFavorite(id){favorites=favorites.includes(id)?favorites.filter(x=>x!==id):[...favorites,id];storage.set('favorites',favorites);updateHearts();toast(favorites.includes(id)?t('Ajouté aux favoris','Saved to favourites'):t('Retiré des favoris','Removed from favourites'))} function updateHearts(){all('[data-save]').forEach(n=>{const yes=favorites.includes(n.dataset.save);n.textContent=yes?'♥':'♡';n.setAttribute('aria-pressed',String(yes));n.setAttribute('aria-label',yes?t('Retirer des favoris','Remove from favourites'):t('Enregistrer','Save'))});all('.favorite').forEach(n=>{const yes=favorites.includes(n.dataset.id);n.textContent=(yes?'♥ ':'♡ ')+(yes?t('Enregistré','Saved'):t('Enregistrer','Save'));n.setAttribute('aria-pressed',String(yes))})} function photo(e,cls){if(!e.image||!safeUrl(e.image.url))return null;const img=el('img');img.src=e.image.url;img.alt='';img.loading='lazy';img.className=cls;img.addEventListener('error',()=>img.remove());return img} function card(e){const c=el('article',undefined,'story-card'),a=el('a');a.href=path('anecdote.php',{id:e.id});const img=photo(e,'story-image');if(img){a.append(img);c.append(a)}c.append(el('p',e.themes.map(themeLabel).join(' · '),'tags'));const save=el('button','♡','save-button');save.dataset.save=e.id;save.addEventListener('click',()=>toggleFavorite(e.id));c.append(save,el('div',String(e.date.year),'story-year'));const h=el('h3'),link=el('a',e.content[lang].short.replace(/^[-−]?\d+\s*[::]\s*/,''));link.href=a.href;h.append(link);c.append(h);const body=e.content[lang].long;c.append(el('p',body.length>165?body.slice(0,162).replace(/\s\S*$/,'')+'…':body));const more=el('a',t('Lire l’histoire','Read the story')+' ↗','card-link');more.href=a.href;c.append(more);if(img)c.append(el('p',e.image.attribution,'image-credit'));return c} function render(list){const grid=$('#stories');grid.replaceChildren(...list.map(card));if(!list.length)grid.append(el('p',t('Aucune anecdote pour cette sélection. Essayez une autre date ou un autre filtre.','No stories in this selection. Try another date or filter.'),'empty'));updateHearts()} function fillThemes(){const grid=$('#theme-choices');for(const x of meta.themes){const label=el('label'),input=el('input');input.type='checkbox';input.value=x.id;input.checked=!preferences.length||preferences.includes(x.id);input.addEventListener('change',countThemes);label.append(input,el('span',`${x.emoji} ${x[lang]}`));grid.append(label)}countThemes();$('#save-preferences').onclick=()=>{const choice=all('#theme-choices input:checked').map(x=>x.value);if(choice.length<5)return;preferences=choice;storage.set('interests',choice);$('#preferences').close();if(page==='home')loadToday();toast(t('Thèmes enregistrés','Interests saved'))};all('[data-preferences]').forEach(b=>b.onclick=()=>$('#preferences').showModal());const ribbon=$('#theme-ribbon');if(ribbon)for(const x of meta.themes){const a=el('a',`${x.emoji} ${x[lang]}`,'theme-pill');a.href=path('calendrier.php',{theme:x.id});ribbon.append(a)}} function countThemes(){const count=all('#theme-choices input:checked').length;$('#theme-count').textContent=`${count} / ${meta.themes.length} `+t('thèmes sélectionnés','interests selected');$('#save-preferences').disabled=count<5} async function loadToday(){const now=new Date(),data=await api({month:now.getMonth()+1,day:now.getDate()});const picks=daily(data.events,dateKey(now),preferences,seen);$('#today-title').textContent=t('Aujourd’hui, ','Today, ')+new Intl.DateTimeFormat(lang,{day:'numeric',month:'long'}).format(now);render(picks);if(picks.length){const e=picks[Math.min(now.getHours()<13?0:now.getHours()<19?1:2,picks.length-1)],hero=$('#hero-story');hero.replaceChildren(el('span','TOUDA / '+t('CE JOUR DANS LE PASSÉ','THIS DAY IN HISTORY'),'orbit-label'));const img=photo(e,'');if(img)hero.prepend(img);hero.append(el('span',String(e.date.year),'giant-year'),el('h2',e.content[lang].short.replace(/^[-−]?\d+\s*[::]\s*/,'')));const a=el('a',t('Découvrir son histoire','Discover the story')+' ↗');a.href=path('anecdote.php',{id:e.id});hero.append(a);if(img)hero.append(el('small',e.image.attribution,'image-credit'))}} let calendarRequest=0;async function loadCalendar(){const request=++calendarRequest;$('#result-count').textContent=t('Recherche…','Loading…');try{const data=await api({month:$('#month').value,day:$('#day').value});if(request!==calendarRequest)return;events=data.events;filterCalendar()}catch{if(request===calendarRequest){$('#result-count').textContent=t('Le catalogue est indisponible. Réessayez avec une connexion.','Catalogue unavailable. Please reconnect and try again.');$('#stories').replaceChildren()}}} function filterCalendar(){let list=events.filter(e=>(!$('#exclude-births').checked||e.kind!=='birth')&&(!$('#theme-filter').value||e.themes.includes($('#theme-filter').value)));const order=$('#sort').value;list.sort((a,b)=>order==='asc'?a.date.year-b.date.year:order==='desc'?b.date.year-a.date.year:order==='random'?hash(dateKey()+a.id)-hash(dateKey()+b.id):importance(b)-importance(a)||b.date.year-a.date.year);render(list);$('#result-count').textContent=`${list.length} `+t('anecdotes','stories');storage.set('sort',order)} function calendar(){const now=new Date();for(let i=1;i<=12;i++){const option=el('option',new Intl.DateTimeFormat(lang,{month:'long'}).format(new Date(2000,i-1,1)));option.value=i;$('#month').append(option)}$('#month').value=now.getMonth()+1;function days(selected){const max=new Date(2000,+$('#month').value,0).getDate();$('#day').replaceChildren();for(let i=1;i<=max;i++){const o=el('option',String(i));o.value=i;$('#day').append(o)}$('#day').value=Math.min(selected,max)}days(now.getDate());for(const x of meta.themes){const o=el('option',`${x.emoji} ${x[lang]}`);o.value=x.id;$('#theme-filter').append(o)}$('#theme-filter').value=new URLSearchParams(location.search).get('theme')||'';$('#sort').value=storage.get('sort','priority');$('#month').onchange=()=>{days(+$('#day').value);loadCalendar()};$('#day').onchange=loadCalendar;for(const id of['theme-filter','sort','exclude-births'])$('#'+id).onchange=filterCalendar;for(const[id,delta]of[['previous',-1],['next',1]])$('#'+id).onclick=()=>{const d=shiftDay(+$('#month').value,+$('#day').value,delta);$('#month').value=d.month;days(d.day);loadCalendar()};loadCalendar()} async function loadFavorites(){const cache=storage.get('savedStories',{}),fresh={};for(let i=0;imerged[id]).filter(Boolean);storage.set('savedStories',Object.fromEntries(events.map(e=>[e.id,e])));const search=()=>{const q=$('#favorite-search').value.toLocaleLowerCase(lang);render(events.filter(e=>`${e.content[lang].short} ${e.content[lang].long} ${e.date.day}/${e.date.month} ${e.date.year} ${e.themes.map(themeLabel).join(' ')}`.toLocaleLowerCase(lang).includes(q)));if(!favorites.length)$('#stories').replaceChildren(el('p',t('Votre collection commence ici. Cliquez sur le cœur d’une anecdote pour la retrouver.','Your collection starts here. Tap a story’s heart to save it.'),'empty'))};$('#favorite-search').oninput=search;$('#clear-favorites').onclick=()=>{if(confirm(t('Supprimer tous les favoris de ce navigateur ?','Remove all favourites from this browser?'))){favorites=[];events=[];storage.set('favorites',[]);storage.set('savedStories',{});search()}};search()} const from64=s=>Uint8Array.from(atob(s.replace(/-/g,'+').replace(/_/g,'/').padEnd(Math.ceil(s.length/4)*4,'=')),c=>c.charCodeAt(0)); async function push(){const status=$('#push-status'),supported=window.isSecureContext&&'serviceWorker'in navigator&&'PushManager'in window&&'Notification'in window;const zone=Intl.DateTimeFormat().resolvedOptions().timeZone;$('#timezone').textContent=t('Fuseau horaire : ','Time zone: ')+zone;const count=$('#push-count');const show=()=>all('#push-times label').forEach((n,i)=>n.hidden=i>=+count.value);count.onchange=show;show();if(!supported){status.textContent=t('Les notifications ne sont pas disponibles ici. Sur iPhone, ajoutez d’abord ce site à l’écran d’accueil.','Notifications are unavailable here. On iPhone, first add this site to your home screen.');return}const reg=await navigator.serviceWorker.ready;const response=await fetch('notifications-api.php');const config=await response.json();if(!config.ready){status.textContent=t('Les rappels sont en préparation : l’envoi serveur doit encore être activé.','Reminders are being prepared: server delivery still needs to be activated.');return}let subscription=await reg.pushManager.getSubscription();status.textContent=subscription?t('Rappels actifs dans ce navigateur.','Reminders are active in this browser.'):t('Le navigateur vous demandera votre accord après votre clic.','Your browser will ask for permission after you click.');$('#push-enable').disabled=false;async function post(action,sub,extra={}){const r=await fetch('notifications-api.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action,subscription:sub,...extra})});if(!r.ok)throw Error('push');return r.json()}$('#push-form').onsubmit=async e=>{e.preventDefault();const button=$('#push-enable');button.disabled=true;try{if(+count.value===0){$('#push-disable').click();return}if(Notification.permission==='denied'){status.textContent=t('Autorisez les notifications dans les réglages du navigateur.','Allow notifications in your browser settings.');return}const permission=await Notification.requestPermission();if(permission!=='granted'){status.textContent=t('Les rappels restent désactivés.','Reminders remain off.');return}subscription=subscription||await reg.pushManager.subscribe({userVisibleOnly:true,applicationServerKey:from64(config.publicKey)});const times=all('#push-times input').slice(0,+count.value).map(x=>x.value);if(new Set(times).size!==times.length){toast(t('Choisissez des horaires différents.','Choose distinct times.'));return}await post('subscribe',subscription.toJSON(),{times,timezone:zone,language:lang,interests:preferences});storage.set('pushTimes',times);status.textContent=t('Vos rappels sont enregistrés.','Your reminders have been saved.')}catch{status.textContent=t('Enregistrement impossible. Réessayez dans quelques instants.','Could not save. Please try again shortly.')}finally{button.disabled=false}};$('#push-disable').onclick=async()=>{try{if(subscription){await post('unsubscribe',subscription.toJSON());await subscription.unsubscribe();subscription=null}status.textContent=t('Rappels désactivés.','Reminders disabled.')}catch{status.textContent=t('Désactivation serveur impossible. Réessayez avec une connexion.','Could not unsubscribe from the server. Reconnect and try again.')}};const saved=storage.get('pushTimes',[]);if(saved.length){count.value=saved.length;all('#push-times input').forEach((n,i)=>{if(saved[i])n.value=saved[i]});show()}} $('#appearance').onclick=()=>{document.body.classList.toggle('dark');storage.set('dark',document.body.classList.contains('dark'))};document.body.classList.toggle('dark',storage.get('dark',matchMedia('(prefers-color-scheme: dark)').matches)); if('serviceWorker'in navigator)navigator.serviceWorker.register('sw.js').catch(()=>{}); window.addEventListener('offline',()=>$('#connection').textContent=t('Hors ligne : seuls les contenus déjà chargés sont disponibles.','Offline: only previously loaded content is available.'));if(!navigator.onLine)window.dispatchEvent(new Event('offline'));window.addEventListener('online',()=>$('#connection').textContent=''); all('.favorite').forEach(n=>n.onclick=()=>toggleFavorite(n.dataset.id));updateHearts();if(page==='story'){const id=$('.story-detail')?.dataset.id;if(id){seen=[...new Set([...seen,id])].slice(-500);storage.set('seen',seen)}$('#share-story')?.addEventListener('click',async()=>{const url=location.href;try{if(navigator.share)await navigator.share({title:document.title,url});else{await navigator.clipboard.writeText(url);toast(t('Lien copié','Link copied'))}}catch{}})} try{meta=await api({action:'meta'});fillThemes();if(page==='home')await loadToday();if(page==='calendar')calendar();if(page==='favorites')await loadFavorites()}catch{if($('#stories'))$('#stories').replaceChildren(el('p',t('Le catalogue est momentanément indisponible. Vérifiez votre connexion puis réessayez.','The catalogue is temporarily unavailable. Check your connection and try again.'),'empty'))}if(page==='notifications')push().catch(()=>$('#push-status').textContent=t('Service de notifications indisponible.','Notification service unavailable.'));