{"scan_id":"22375397-1a27-454d-9187-41578701c6d8","url":"https://ayidna-dashboard.pages.dev/","final_url":"https://ayidna-dashboard.pages.dev/","status":"completed","scan_type":"public","title":"Mon Dashboard","screenshot":"/api/v1/screenshot/22375397-1a27-454d-9187-41578701c6d8.png","submitted_at":"2026-08-12T08:15:51.107892Z","completed_at":"2026-08-12T08:16:58.389276Z","load_time":0.7261395454406738,"load_time_comparison":{"band":"very_fast","label":"Very Fast","percentile":19,"faster_than_pct":81,"median":3.62,"p25":1.05,"p50":3.62,"p75":11.42,"sample_size":429305},"links":[{"href":"https://ayidna-dashboard.pages.dev/index.html","text":"","external":false},{"href":"https://ayidna-dashboard.pages.dev/watchlist.html","text":"","external":false},{"href":"https://ayidna-dashboard.pages.dev/music.html","text":"","external":false}],"forms":[],"cookies":[],"scripts":[{"src":null,"size":89607,"type":"inline","source":"dom","content":"\n/* ══════════════════════════════════════\n   STATE.JS — Persistent state\n══════════════════════════════════════ */\n\nconst DEFAULT = {\n  username: 'admin',\n  password: 'admin',\n  displayName: 'Ayidna',\n  dark: true,\n  accent: '#6c8eff',\n  lang: 'fr',\n  bg: { type: 'none', url: '', data: '', blur: 8, opacity: 25 },\n  todoTabs: ['Perso','Quotidien','École','Langues'],\n  activeTodoTab: 'Perso',\n  showDone: false,\n  todos: {},\n  calEvents: {},\n  sections: [\n    { id: 'personal', label: 'Mes Sites Personnels', type: 'personal' },\n    { id: 'general',  label: 'Sites & Outils',       type: 'general'  },\n    { id: 'manga',    label: 'Manga & Scan',          type: 'general'  },\n  ],\n  sites: [\n    // General\n    { id:'yt',      name:'YouTube',    url:'https://youtube.com',               img:'', section:'general',  desc:'Vidéos en streaming' },\n    { id:'gh',      name:'GitHub',     url:'https://github.com',                img:'', section:'general',  desc:'Hébergement de code' },\n    { id:'cl',      name:'Claude',     url:'https://claude.ai',                 img:'', section:'general',  desc:'IA Anthropic' },\n    { id:'cgpt',    name:'ChatGPT',    url:'https://chatgpt.com',               img:'', section:'general',  desc:'IA OpenAI' },\n    { id:'gem',     name:'Gemini',     url:'https://gemini.google.com',         img:'', section:'general',  desc:'IA Google' },\n    { id:'ggl',     name:'Google',     url:'https://google.com',                img:'', section:'general',  desc:'Moteur de recherche' },\n    { id:'tw',      name:'Twitch',     url:'https://twitch.tv',                 img:'', section:'general',  desc:'Streaming live' },\n    { id:'gml',     name:'Gmail',      url:'https://mail.google.com',           img:'', section:'general',  desc:'Messagerie Google' },\n    { id:'otl',     name:'Outlook',    url:'https://outlook.live.com',          img:'', section:'general',  desc:'Messagerie Microsoft' },\n    { id:'gsh',     name:'G. Sheets',  url:'https://sheets.google.com',         img:'', section:'general',  desc:'Tableur Google' },\n    { id:'gdc',     name:'G. Docs',    url:'https://docs.google.com',           img:'', section:'general',  desc:'Traitement de texte' },\n    { id:'mal',     name:'MyAnimeList',url:'https://myanimelist.net',           img:'', section:'general',  desc:'Anime & Manga tracker' },\n    { id:'imt',     name:'MyServices', url:'https://myservices.imt-nord-europe.fr', img:'', section:'general', desc:'Services IMT' },\n    // Personal\n    { id:'cv',      name:'Mon CV',         url:'#', img:'', section:'personal', desc:'Portfolio & CV en ligne',   color:'#6c8eff' },\n    { id:'apply',   name:'Apply-Location', url:'#', img:'', section:'personal', desc:'Suivi des candidatures',    color:'#a78bfa' },\n  ],\n  notifications: [],\n  chatHistory: [],\n};\n\nfunction deepMerge(target, defaults) {\n  for (const k in defaults) {\n    if (!(k in target)) {\n      target[k] = JSON.parse(JSON.stringify(defaults[k]));\n    } else if (typeof defaults[k] === 'object' && !Array.isArray(defaults[k]) && defaults[k] !== null) {\n      if (typeof target[k] !== 'object') target[k] = {};\n      deepMerge(target[k], defaults[k]);\n    }\n  }\n  return target;\n}\n\nlet S; // global state\n\nconst STATE_VERSION = 4;\n\nfunction loadState() {\n  try {\n    const raw = localStorage.getItem('dash_v2');\n    if (!raw) {\n      S = JSON.parse(JSON.stringify(DEFAULT));\n      return;\n    }\n    const saved = JSON.parse(raw);\n\n    // Migration: on version bump, reset credentials and save\n    if (!saved._version || saved._version < STATE_VERSION) {\n      S = deepMerge(saved, JSON.parse(JSON.stringify(DEFAULT)));\n      S.username    = DEFAULT.username;   // admin\n      S.password    = DEFAULT.password;   // admin\n      S._version    = STATE_VERSION;\n      try { localStorage.setItem('dash_v2', JSON.stringify(S)); } catch {}\n    } else {\n      S = deepMerge(saved, JSON.parse(JSON.stringify(DEFAULT)));\n    }\n  } catch(e) {\n    console.warn('State load error, resetting:', e);\n    S = JSON.parse(JSON.stringify(DEFAULT));\n  }\n}\n\nfunction saveState() {\n  // Don't save bg data (base64) in localStorage if too large — use separate key\n  const toSave = JSON.parse(JSON.stringify(S));\n  const bgData = toSave.bg?.data || '';\n  if (bgData.length > 50000) {\n    try { localStorage.setItem('dash_bg_data', bgData); } catch {}\n    toSave.bg.data = '__ref__';\n  }\n  try { localStorage.setItem('dash_v2', JSON.stringify(toSave)); } catch(e) {\n    toSave.chatHistory = [];\n    try { localStorage.setItem('dash_v2', JSON.stringify(toSave)); } catch {}\n  }\n  // Trigger cloud sync if configured (debounced)\n  if (typeof scheduleSyncSave === 'function') scheduleSyncSave();\n}\n\nfunction loadBgData() {\n  if (S.bg?.data === '__ref__') {\n    S.bg.data = localStorage.getItem('dash_bg_data') || '';\n  }\n}\n\n// Helpers\nfunction genId() { return 's_' + Date.now() + '_' + Math.random().toString(36).slice(2,6); }\nfunction escHtml(s) { return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;'); }\nfunction toast(msg, dur=2200) {\n  const el = document.getElementById('toast');\n  el.textContent = msg; el.classList.add('show');\n  clearTimeout(el._t);\n  el._t = setTimeout(() => el.classList.remove('show'), dur);\n}\nfunction getFavicon(url) {\n  try { return `https://www.google.com/s2/favicons?domain=${new URL(url).hostname}&sz=64`; } catch { return ''; }\n}\n\nloadState();\nloadBgData();\n\n/* ══════════════════════════════════════\n   I18N.JS\n══════════════════════════════════════ */\n\nconst LANG = {\n  fr: {\n    todo: 'Liste de tâches', translate: 'Traduction', calendar: 'Calendrier',\n    welcome: 'Bonjour',\n    months: ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'],\n    days: ['Lu','Ma','Me','Je','Ve','Sa','Di'],\n    add_task: 'Nouvelle tâche…',\n    search_placeholder: 'Rechercher…',\n    no_results: 'Aucun résultat',\n  },\n  en: {\n    todo: 'Task List', translate: 'Translation', calendar: 'Calendar',\n    welcome: 'Hello',\n    months: ['January','February','March','April','May','June','July','August','September','October','November','December'],\n    days: ['Mo','Tu','We','Th','Fr','Sa','Su'],\n    add_task: 'New task…',\n    search_placeholder: 'Search…',\n    no_results: 'No results',\n  },\n  zh: {\n    todo: '任务列表', translate: '翻译', calendar: '日历',\n    welcome: '你好',\n    months: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],\n    days: ['一','二','三','四','五','六','日'],\n    add_task: '新任务…',\n    search_placeholder: '搜索…',\n    no_results: '无结果',\n  }\n};\n\nfunction t(key) {\n  return (LANG[S.lang] || LANG.fr)[key] || key;\n}\n\nfunction applyI18n() {\n  document.querySelectorAll('[data-i18n]').forEach(el => {\n    const v = t(el.dataset.i18n);\n    if (v) el.textContent = v;\n  });\n  const si = document.getElementById('search-input');\n  if (si) si.placeholder = t('search_placeholder');\n  const ti = document.getElementById('todo-input');\n  if (ti) ti.placeholder = t('add_task');\n\n  // Update welcome\n  const wg = document.getElementById('welcome-greeting');\n  if (wg) wg.textContent = t('welcome');\n\n  // Date\n  const locale = { fr:'fr-FR', en:'en-US', zh:'zh-CN' }[S.lang] || 'fr-FR';\n  const dt = document.getElementById('date-text');\n  if (dt) dt.textContent = new Date().toLocaleDateString(locale, { weekday:'long', year:'numeric', month:'long', day:'numeric' });\n}\n\n/* ══════════════════════════════════════\n   THEME.JS — Dark/Light, Accent, Background\n══════════════════════════════════════ */\n\nconst ACCENTS = ['#6c8eff','#a78bfa','#34d399','#f87171','#fbbf24','#38bdf8','#fb923c','#ec4899'];\n\nfunction applyTheme() {\n  document.body.classList.toggle('light', !S.dark);\n  document.body.classList.toggle('dark', S.dark);\n  document.documentElement.style.setProperty('--accent', S.accent);\n  applyBg();\n}\n\nfunction toggleDark() {\n  S.dark = !S.dark; saveState(); applyTheme();\n  document.getElementById('dark-toggle').classList.toggle('on', S.dark);\n}\n\nfunction setAccent(el) {\n  document.querySelectorAll('.color-opt').forEach(e => e.classList.remove('active'));\n  el.classList.add('active');\n  S.accent = el.dataset.color; saveState(); applyTheme();\n}\n\nfunction applyBg() {\n  const bg = S.bg;\n  const imgEl = document.getElementById('bg-img');\n  const overlayEl = document.getElementById('bg-overlay');\n  const src = bg.data || bg.url;\n  if (src && bg.type !== 'none') {\n    imgEl.style.backgroundImage = `url('${src}')`;\n    imgEl.style.filter = `blur(${bg.blur}px)`;\n    imgEl.style.transform = 'scale(1.05)'; // prevent blur edge\n    imgEl.classList.add('active');\n    overlayEl.style.opacity = (bg.opacity / 100);\n  } else {\n    imgEl.classList.remove('active');\n    imgEl.style.backgroundImage = '';\n    overlayEl.style.opacity = S.dark ? '1' : '1';\n  }\n}\n\nfunction setBg(type) {\n  S.bg.type = type;\n  if (type === 'none') { S.bg.url = ''; S.bg.data = ''; }\n  saveState(); applyBg();\n}\n\nfunction setBgUrl() {\n  const url = document.getElementById('bg-url-input').value.trim();\n  if (!url) return;\n  S.bg.url = url; S.bg.data = ''; S.bg.type = 'url';\n  saveState(); applyBg(); toast('Image de fond appliquée');\n}\n\nfunction setBgBlur(val) {\n  S.bg.blur = parseInt(val); saveState(); applyBg();\n}\nfunction setBgOpacity(val) {\n  S.bg.opacity = parseInt(val); saveState(); applyBg();\n}\n\nfunction triggerBgFile() {\n  document.getElementById('bg-file-input').click();\n}\n\nfunction loadBgFile(input) {\n  const file = input.files[0];\n  if (!file) return;\n  const reader = new FileReader();\n  reader.onload = e => {\n    S.bg.data = e.target.result;\n    S.bg.url = '';\n    S.bg.type = 'file';\n    saveState(); applyBg(); toast('Image de fond appliquée');\n  };\n  reader.readAsDataURL(file);\n}\n\nfunction buildColorOptions() {\n  const wrap = document.getElementById('color-options');\n  wrap.innerHTML = '';\n  ACCENTS.forEach(c => {\n    const d = document.createElement('div');\n    d.className = 'color-opt' + (S.accent === c ? ' active' : '');\n    d.style.background = c;\n    d.dataset.color = c;\n    d.onclick = () => setAccent(d);\n    wrap.appendChild(d);\n  });\n}\n\nfunction buildLangOptions() {\n  const wrap = document.getElementById('lang-opts');\n  wrap.innerHTML = '';\n  [['fr','🇫🇷 FR'],['en','🇬🇧 EN'],['zh','🇨🇳 中文']].forEach(([code, label]) => {\n    const btn = document.createElement('button');\n    btn.className = 'lang-btn' + (S.lang === code ? ' active' : '');\n    btn.dataset.lang = code;\n    btn.textContent = label;\n    btn.onclick = () => setLang(btn);\n    wrap.appendChild(btn);\n  });\n}\n\nfunction setLang(el) {\n  document.querySelectorAll('.lang-btn').forEach(e => e.classList.remove('active'));\n  el.classList.add('active');\n  S.lang = el.dataset.lang; saveState(); applyI18n();\n  renderCalendar(); // month names change\n}\n\nfunction toggleSettings() {\n  document.getElementById('settings-panel').classList.toggle('open');\n  document.getElementById('settings-overlay').classList.toggle('open');\n}\n\nfunction updateDisplayName(v) {\n  S.displayName = v;\n  saveState();\n  const el = document.getElementById('user-name');\n  if (el) el.textContent = v || 'Explorer';\n}\n\nfunction changeCredentials() {\n  const uEl = document.getElementById('settings-username');\n  const pEl = document.getElementById('settings-password');\n  const newUser = uEl?.value.trim();\n  const newPass = pEl?.value;\n  if (!newUser) { toast('L\\'identifiant ne peut pas être vide'); return; }\n  S.username = newUser;\n  if (newPass) S.password = newPass;\n  saveState();\n  if (pEl) pEl.value = '';\n  toast('Identifiants mis à jour ✓');\n}\n\n// Keep old name as alias\nfunction changePassword() { changeCredentials(); }\n\n// Sync bg sliders to state\nfunction syncBgControls() {\n  const blurEl = document.getElementById('bg-blur');\n  const opEl = document.getElementById('bg-opacity');\n  if (blurEl) blurEl.value = S.bg.blur ?? 8;\n  if (opEl)   opEl.value  = S.bg.opacity ?? 25;\n  const urlEl = document.getElementById('bg-url-input');\n  if (urlEl && S.bg.url) urlEl.value = S.bg.url;\n}\n\n/* ══════════════════════════════════════\n   TODO.JS — Tasks + Category Drag & Drop\n══════════════════════════════════════ */\n\n// ── Tab drag state ────────────────────────────\nlet tabDragSrc = null;\nlet tabDragClone = null;\nlet tabDragOverIdx = null;\n\n// ── Tabs ──────────────────────────────────────\nfunction renderTodoTabs() {\n  const row = document.getElementById('todo-tabs-row');\n  row.innerHTML = '';\n\n  S.todoTabs.forEach((tab, idx) => {\n    const open = (S.todos[tab] || []).filter(i => !i.done).length;\n\n    const wrap = document.createElement('div');\n    wrap.className = 'todo-tab-wrap';\n    wrap.dataset.idx = idx;\n    wrap.draggable = true;\n\n    const btn = document.createElement('button');\n    btn.className = 'todo-tab' + (S.activeTodoTab === tab ? ' active' : '');\n    btn.innerHTML = `\n      <svg class=\"tab-drag-handle\" width=\"8\" height=\"12\" viewBox=\"0 0 8 12\" fill=\"currentColor\" style=\"opacity:.4;flex-shrink:0;margin-right:4px\">\n        <circle cx=\"2\" cy=\"2\" r=\"1.2\"/><circle cx=\"6\" cy=\"2\" r=\"1.2\"/>\n        <circle cx=\"2\" cy=\"6\" r=\"1.2\"/><circle cx=\"6\" cy=\"6\" r=\"1.2\"/>\n        <circle cx=\"2\" cy=\"10\" r=\"1.2\"/><circle cx=\"6\" cy=\"10\" r=\"1.2\"/>\n      </svg>\n      ${escHtml(tab)} <span class=\"todo-count\">${open}</span>`;\n    btn.onclick = () => selectTodoTab(tab);\n\n    const del = document.createElement('button');\n    del.className = 'todo-tab-del';\n    del.title = 'Supprimer'; del.textContent = '×';\n    del.onclick = e => { e.stopPropagation(); deleteTodoTab(tab); };\n    btn.appendChild(del);\n    wrap.appendChild(btn);\n\n    // Tab drag & drop\n    wrap.addEventListener('dragstart', e => {\n      tabDragSrc = idx;\n      e.dataTransfer.effectAllowed = 'move';\n      // Ghost: semi-transparent clone handled by browser default (good enough for tabs)\n      setTimeout(() => wrap.style.opacity = '0.35', 0);\n    });\n    wrap.addEventListener('dragend', () => {\n      wrap.style.opacity = '';\n      tabDragSrc = null;\n      // Remove all indicators\n      document.querySelectorAll('.tab-drop-indicator').forEach(el => el.remove());\n      renderTodoTabs();\n    });\n    wrap.addEventListener('dragover', e => {\n      e.preventDefault();\n      if (tabDragSrc === null || tabDragSrc === idx) return;\n      document.querySelectorAll('.tab-drop-indicator').forEach(el => el.remove());\n      const indicator = document.createElement('div');\n      indicator.className = 'tab-drop-indicator';\n      // Insert before or after based on mouse X\n      const rect = wrap.getBoundingClientRect();\n      const before = e.clientX < rect.left + rect.width / 2;\n      if (before) row.insertBefore(indicator, wrap);\n      else wrap.after(indicator);\n      tabDragOverIdx = before ? idx : idx + 1;\n    });\n    wrap.addEventListener('drop', e => {\n      e.preventDefault();\n      if (tabDragSrc === null || tabDragSrc === tabDragOverIdx) return;\n      const [moved] = S.todoTabs.splice(tabDragSrc, 1);\n      let insertAt = tabDragOverIdx > tabDragSrc ? tabDragOverIdx - 1 : tabDragOverIdx;\n      S.todoTabs.splice(insertAt, 0, moved);\n      saveState();\n    });\n\n    row.appendChild(wrap);\n  });\n\n  const addBtn = document.createElement('button');\n  addBtn.className = 'add-tab-btn';\n  addBtn.textContent = '+ Catégorie';\n  addBtn.onclick = () => document.getElementById('cat-modal-bg').classList.add('open');\n  row.appendChild(addBtn);\n}\n\nfunction selectTodoTab(tab) {\n  S.activeTodoTab = tab; saveState(); renderTodoTabs(); renderTodos();\n}\n\nfunction deleteTodoTab(tab) {\n  if (S.todoTabs.length <= 1) { toast('Impossible de supprimer la dernière catégorie'); return; }\n  if (!confirm(`Supprimer \"${tab}\" et ses tâches ?`)) return;\n  S.todoTabs = S.todoTabs.filter(t => t !== tab);\n  delete S.todos[tab];\n  if (S.activeTodoTab === tab) S.activeTodoTab = S.todoTabs[0];\n  saveState(); renderTodoTabs(); renderTodos();\n  toast(`Catégorie \"${tab}\" supprimée`);\n}\n\nfunction saveCatModal() {\n  const name = document.getElementById('cat-modal-name').value.trim();\n  if (!name) return;\n  if (S.todoTabs.includes(name)) { toast('Catégorie déjà existante'); return; }\n  S.todoTabs.push(name); saveState();\n  document.getElementById('cat-modal-bg').classList.remove('open');\n  document.getElementById('cat-modal-name').value = '';\n  renderTodoTabs(); toast(`Catégorie \"${name}\" créée`);\n}\n\nfunction closeCatModal(e) {\n  if (!e || e.target === document.getElementById('cat-modal-bg'))\n    document.getElementById('cat-modal-bg').classList.remove('open');\n}\n\n// ── Render Todos ──────────────────────────────\nfunction renderTodos() {\n  const list = document.getElementById('todo-list');\n  list.innerHTML = '';\n  const all = S.todos[S.activeTodoTab] || [];\n  const items = S.showDone ? all : all.filter(i => !i.done);\n  if (!items.length) {\n    list.innerHTML = `<li class=\"todo-empty\">${S.showDone ? 'Aucune tâche' : 'Toutes les tâches sont terminées 🎉'}</li>`;\n    return;\n  }\n  items.forEach(item => list.appendChild(makeTodoItem(item, all.indexOf(item))));\n  initTodoDrag(list);\n}\n\nfunction makeTodoItem(item, realIdx) {\n  const li = document.createElement('li');\n  li.className = 'todo-item' + (item.done ? ' done-item' : '');\n  li.dataset.realIdx = realIdx;\n  const dateStr = item.addedAt ? formatTodoDate(item.addedAt) : '';\n  li.innerHTML = `\n    <div class=\"drag-handle\" title=\"Réordonner\">\n      <svg width=\"10\" height=\"16\" viewBox=\"0 0 10 16\" fill=\"currentColor\">\n        <circle cx=\"3\" cy=\"3\" r=\"1.5\"/><circle cx=\"7\" cy=\"3\" r=\"1.5\"/>\n        <circle cx=\"3\" cy=\"8\" r=\"1.5\"/><circle cx=\"7\" cy=\"8\" r=\"1.5\"/>\n        <circle cx=\"3\" cy=\"13\" r=\"1.5\"/><circle cx=\"7\" cy=\"13\" r=\"1.5\"/>\n      </svg>\n    </div>\n    <div class=\"todo-check ${item.done?'done':''}\" onclick=\"toggleTodo(${realIdx})\"></div>\n    <div class=\"todo-info\">\n      <span class=\"todo-text ${item.done?'done':''}\">${escHtml(item.text)}</span>\n      ${dateStr ? `<span class=\"todo-date\">${dateStr}</span>` : ''}\n    </div>\n    <div class=\"todo-prio\">\n      ${[0,1,2].map(p=>`<div class=\"prio-dot prio-${p}${item.prio===p?' active':''}\" onclick=\"setPrio(${realIdx},${p})\"></div>`).join('')}\n    </div>\n    <button class=\"todo-del\" onclick=\"delTodo(${realIdx})\">×</button>`;\n  return li;\n}\n\nfunction formatTodoDate(ts) {\n  const d = new Date(ts), now = new Date();\n  const diff = Math.floor((now - d) / 86400000);\n  if (diff === 0) return \"Aujourd'hui\";\n  if (diff === 1) return 'Hier';\n  if (diff < 7)  return `Il y a ${diff} j.`;\n  return d.toLocaleDateString('fr-FR', {day:'numeric', month:'short'});\n}\n\n// ── Todo actions ──────────────────────────────\nfunction addTodo() {\n  const inp = document.getElementById('todo-input');\n  const text = inp.value.trim(); if (!text) return;\n  if (!S.todos[S.activeTodoTab]) S.todos[S.activeTodoTab] = [];\n  S.todos[S.activeTodoTab].unshift({ text, done:false, prio:0, addedAt:Date.now() });\n  inp.value = ''; saveState(); renderTodos(); renderTodoTabs();\n}\nfunction toggleTodo(idx) {\n  const item = S.todos[S.activeTodoTab]?.[idx]; if (!item) return;\n  item.done = !item.done; saveState(); renderTodos(); renderTodoTabs();\n}\nfunction delTodo(idx) {\n  S.todos[S.activeTodoTab]?.splice(idx, 1); saveState(); renderTodos(); renderTodoTabs();\n}\nfunction setPrio(idx, p) {\n  const item = S.todos[S.activeTodoTab]?.[idx]; if (!item) return;\n  item.prio = p; saveState(); renderTodos();\n}\nfunction toggleShowDone() {\n  S.showDone = !S.showDone; saveState();\n  document.getElementById('show-done-btn').classList.toggle('active', S.showDone);\n  document.getElementById('show-done-label').textContent = S.showDone ? 'Masquer terminées' : 'Voir terminées';\n  renderTodos();\n}\n\n// ── Task Drag & Drop (item moves with cursor) ──\nlet todoFloating = null;\nlet todoPlaceholder = null;\n\nfunction initTodoDrag(list) {\n  list.querySelectorAll('.todo-item .drag-handle').forEach(handle => {\n    handle.addEventListener('mousedown', e => beginTodoDrag(e, handle.closest('.todo-item'), list));\n    handle.addEventListener('touchstart', e => {\n      const t = e.touches[0];\n      beginTodoDrag({ clientX:t.clientX, clientY:t.clientY, preventDefault:()=>e.preventDefault() }, handle.closest('.todo-item'), list);\n    }, { passive:false });\n  });\n}\n\nfunction beginTodoDrag(e, item, list) {\n  e.preventDefault();\n  const rect = item.getBoundingClientRect();\n  const offsetX = e.clientX - rect.left;\n  const offsetY = e.clientY - rect.top;\n\n  // Float the real item\n  item.style.cssText = `position:fixed;width:${rect.width}px;top:${rect.top}px;left:${rect.left}px;z-index:9999;box-shadow:0 16px 48px rgba(0,0,0,.5);transform:rotate(1.5deg) scale(1.03);transition:box-shadow .15s,transform .15s;pointer-events:none;margin:0;border-radius:var(--r-sm);background:var(--surface3);`;\n  todoFloating = item;\n\n  // Placeholder\n  todoPlaceholder = document.createElement('li');\n  todoPlaceholder.className = 'todo-placeholder';\n  todoPlaceholder.style.height = rect.height + 'px';\n  list.insertBefore(todoPlaceholder, item.nextSibling);\n\n  function move(cx, cy) {\n    todoFloating.style.top  = (cy - offsetY) + 'px';\n    todoFloating.style.left = (cx - offsetX) + 'px';\n    const lb = list.getBoundingClientRect();\n    if      (cy < lb.top + 50)    list.scrollTop -= 7;\n    else if (cy > lb.bottom - 50) list.scrollTop += 7;\n    const siblings = [...list.querySelectorAll('.todo-item')].filter(el => el !== todoFloating);\n    let insertBefore = null;\n    for (const sib of siblings) {\n      const sb = sib.getBoundingClientRect();\n      if (cy < sb.top + sb.height / 2) { insertBefore = sib; break; }\n    }\n    if (insertBefore) list.insertBefore(todoPlaceholder, insertBefore);\n    else {\n      const lastItem = [...list.querySelectorAll('.todo-item')].filter(el=>el!==todoFloating).pop();\n      if (lastItem) lastItem.after(todoPlaceholder);\n      else list.appendChild(todoPlaceholder);\n    }\n  }\n\n  function onMouseMove(e) { move(e.clientX, e.clientY); }\n  function onTouchMove(e) { const t=e.touches[0]; move(t.clientX, t.clientY); }\n\n  function finish() {\n    document.removeEventListener('mousemove', onMouseMove);\n    document.removeEventListener('mouseup', finish);\n    document.removeEventListener('touchmove', onTouchMove);\n    document.removeEventListener('touchend', finish);\n\n    const phRect = todoPlaceholder.getBoundingClientRect();\n    todoFloating.style.transition = 'top .18s cubic-bezier(.4,0,.2,1),left .18s,transform .18s';\n    todoFloating.style.top    = phRect.top + 'px';\n    todoFloating.style.left   = phRect.left + 'px';\n    todoFloating.style.transform = 'rotate(0deg) scale(1)';\n\n    setTimeout(() => {\n      const all = S.todos[S.activeTodoTab] || [];\n      const shown = S.showDone ? all : all.filter(i => !i.done);\n      const hidden = all.filter(i => !shown.includes(i));\n      const srcRealIdx = parseInt(todoFloating.dataset.realIdx);\n      const srcItem = all[srcRealIdx];\n\n      // Find new position from placeholder\n      const visItems = [...list.querySelectorAll('.todo-item')].filter(el=>el!==todoFloating);\n      const phPos = [...list.children].filter(c => c.classList.contains('todo-item') || c === todoPlaceholder).indexOf(todoPlaceholder);\n      const newShown = shown.filter(it => it !== srcItem);\n      newShown.splice(Math.min(phPos, newShown.length), 0, srcItem);\n\n      S.todos[S.activeTodoTab] = [...newShown, ...hidden];\n      todoFloating.style.cssText = '';\n      todoPlaceholder.remove();\n      todoFloating = null; todoPlaceholder = null;\n      saveState(); renderTodos();\n    }, 180);\n  }\n\n  document.addEventListener('mousemove', onMouseMove);\n  document.addEventListener('mouseup', finish);\n  document.addEventListener('touchmove', onTouchMove, {passive:false});\n  document.addEventListener('touchend', finish);\n}\n\ndocument.addEventListener('DOMContentLoaded', () => {\n  const inp = document.getElementById('todo-input');\n  if (inp) inp.addEventListener('keydown', e => { if(e.key==='Enter') addTodo(); });\n  const cbg = document.getElementById('cat-modal-bg');\n  if (cbg) cbg.addEventListener('click', closeCatModal);\n  const cn = document.getElementById('cat-modal-name');\n  if (cn) cn.addEventListener('keydown', e => { if(e.key==='Enter') saveCatModal(); });\n  const sdBtn = document.getElementById('show-done-btn');\n  if (sdBtn) sdBtn.classList.toggle('active', S.showDone);\n  const sdLabel = document.getElementById('show-done-label');\n  if (sdLabel) sdLabel.textContent = S.showDone ? 'Masquer terminées' : 'Voir terminées';\n});\n\n/* ══════════════════════════════════════\n   CALENDAR.JS\n══════════════════════════════════════ */\n\nlet calYear, calMonth, selectedDate = null;\n\nfunction initCalendar() {\n  const today = new Date();\n  calYear = today.getFullYear();\n  calMonth = today.getMonth();\n  renderCalendar();\n}\n\nfunction renderCalendar() {\n  const months = t('months');\n  const days = t('days');\n  document.getElementById('cal-month-label').textContent = `${months[calMonth]} ${calYear}`;\n\n  const grid = document.getElementById('cal-grid');\n  grid.innerHTML = '';\n\n  // Day names\n  days.forEach(d => {\n    const el = document.createElement('div');\n    el.className = 'cal-day-name';\n    el.textContent = d;\n    grid.appendChild(el);\n  });\n\n  const today = new Date();\n  const firstDay = new Date(calYear, calMonth, 1).getDay();\n  const offset = (firstDay === 0) ? 6 : firstDay - 1;\n  const daysInMonth = new Date(calYear, calMonth + 1, 0).getDate();\n  const prevDays = new Date(calYear, calMonth, 0).getDate();\n\n  // Prev month tail\n  for (let i = offset - 1; i >= 0; i--) {\n    const el = document.createElement('div');\n    el.className = 'cal-day other-month';\n    el.textContent = prevDays - i;\n    grid.appendChild(el);\n  }\n\n  // Current month\n  for (let d = 1; d <= daysInMonth; d++) {\n    const el = document.createElement('div');\n    el.className = 'cal-day';\n    const key = dateKey(calYear, calMonth, d);\n    const isToday = d === today.getDate() && calMonth === today.getMonth() && calYear === today.getFullYear();\n    if (isToday) el.classList.add('today');\n    if (S.calEvents[key]?.length) el.classList.add('has-event');\n    if (selectedDate === key) el.classList.add('selected');\n    el.textContent = d;\n    el.onclick = () => selectCalDate(key);\n    grid.appendChild(el);\n  }\n\n  // Next month padding\n  const filled = offset + daysInMonth;\n  const remaining = filled % 7 === 0 ? 0 : 7 - (filled % 7);\n  for (let i = 1; i <= remaining; i++) {\n    const el = document.createElement('div');\n    el.className = 'cal-day other-month';\n    el.textContent = i;\n    grid.appendChild(el);\n  }\n}\n\nfunction dateKey(y, m, d) {\n  return `${y}-${String(m+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;\n}\n\nfunction changeMonth(dir) {\n  calMonth += dir;\n  if (calMonth > 11) { calMonth = 0; calYear++; }\n  if (calMonth < 0)  { calMonth = 11; calYear--; }\n  renderCalendar();\n}\n\nfunction selectCalDate(key) {\n  selectedDate = key;\n  renderCalendar();\n  const panel = document.getElementById('cal-event-panel');\n  panel.classList.add('open');\n\n  const [y, m, d] = key.split('-');\n  const months = t('months');\n  document.getElementById('cal-event-date').textContent =\n    `${parseInt(d)} ${months[parseInt(m)-1]} ${y}`;\n\n  renderCalEvents(key);\n}\n\nfunction renderCalEvents(key) {\n  const evs = S.calEvents[key] || [];\n  const list = document.getElementById('cal-event-list');\n  list.innerHTML = '';\n  if (!evs.length) {\n    list.innerHTML = '<div class=\"cal-no-events\">Aucun évènement</div>';\n    return;\n  }\n  evs.forEach((ev, i) => {\n    const d = document.createElement('div');\n    d.className = 'cal-event-item';\n    d.innerHTML = `\n      <div class=\"cal-event-dot\"></div>\n      <span>${escHtml(ev)}</span>\n      <button class=\"cal-event-del\" onclick=\"delCalEvent('${key}',${i})\">×</button>\n    `;\n    list.appendChild(d);\n  });\n}\n\nfunction addCalEvent() {\n  const inp = document.getElementById('cal-event-input');\n  const v = inp.value.trim();\n  if (!v || !selectedDate) return;\n  if (!S.calEvents[selectedDate]) S.calEvents[selectedDate] = [];\n  S.calEvents[selectedDate].push(v);\n  inp.value = '';\n  saveState(); renderCalEvents(selectedDate); renderCalendar();\n}\n\nfunction delCalEvent(key, i) {\n  S.calEvents[key].splice(i, 1);\n  if (!S.calEvents[key].length) delete S.calEvents[key];\n  saveState(); renderCalEvents(key); renderCalendar();\n}\n\ndocument.addEventListener('DOMContentLoaded', () => {\n  const inp = document.getElementById('cal-event-input');\n  if (inp) inp.addEventListener('keydown', e => { if(e.key==='Enter') addCalEvent(); });\n});\n\n/* ══════════════════════════════════════\n   SITES.JS — Sections & Site Cards\n══════════════════════════════════════ */\n\nlet modalCtx = null;\nlet editMode = false;\nlet dragSite = null; // { id, fromSection }\nlet dragGhost = null;\n\n// ── Render All Sections ──────────────────────\nfunction renderAllSections() {\n  const container = document.getElementById('sections-container');\n  container.innerHTML = '';\n  S.sections.forEach(sec => {\n    const sites = S.sites.filter(s => s.section === sec.id);\n    container.appendChild(buildSectionCard(sec, sites));\n  });\n  renderSectionManager();\n  populateModalSectionSelect();\n  updateEditBar();\n}\n\nfunction buildSectionCard(sec, sites) {\n  const card = document.createElement('section');\n  card.className = 'card sites-section';\n  card.dataset.sectionId = sec.id;\n\n  const header = document.createElement('div');\n  header.className = 'card-header';\n  header.innerHTML = `\n    <div class=\"section-header-inner\">\n      <span class=\"card-title\">${escHtml(sec.label)}</span>\n      <button class=\"section-del-btn edit-only\" onclick=\"deleteSection('${sec.id}')\" title=\"Supprimer\">×</button>\n    </div>`;\n  card.appendChild(header);\n\n  const grid = document.createElement('div');\n  grid.className = sec.type === 'personal' ? 'personal-grid' : 'sites-grid';\n  grid.dataset.sectionId = sec.id;\n  grid.dataset.sectionType = sec.type;\n\n  // Drop zone events\n  grid.addEventListener('dragover', onGridDragOver);\n  grid.addEventListener('dragleave', onGridDragLeave);\n  grid.addEventListener('drop', e => onGridDrop(e, sec.id));\n\n  sites.forEach(site => {\n    const el = sec.type === 'personal' ? buildPersonalCard(site) : buildSiteCard(site);\n    grid.appendChild(el);\n  });\n\n  // Add button - edit mode only\n  const addBtn = document.createElement('button');\n  addBtn.className = (sec.type === 'personal' ? 'add-personal-btn' : 'add-site-btn') + ' edit-only';\n  addBtn.innerHTML = `<span class=\"plus\">+</span>${sec.type === 'personal' ? 'Nouveau' : 'Ajouter'}`;\n  addBtn.onclick = () => openModal(sec.id, sec.type);\n  grid.appendChild(addBtn);\n\n  card.appendChild(grid);\n  return card;\n}\n\n// ── Known brand colors (fallback when canvas blocked by CORS) ──\nconst BRAND_COLORS = {\n  'youtube.com':               '#FF0000',\n  'github.com':                '#24292e',\n  'claude.ai':                 '#D97757',\n  'chatgpt.com':               '#10a37f',\n  'openai.com':                '#10a37f',\n  'gemini.google.com':         '#4285F4',\n  'google.com':                '#4285F4',\n  'twitch.tv':                 '#9146FF',\n  'mail.google.com':           '#EA4335',\n  'outlook.live.com':          '#0078D4',\n  'outlook.com':               '#0078D4',\n  'sheets.google.com':         '#34A853',\n  'docs.google.com':           '#4285F4',\n  'myanimelist.net':           '#2E51A2',\n  'myservices.imt-nord-europe.fr': '#003087',\n  'notion.so':                 '#000000',\n  'figma.com':                 '#F24E1E',\n  'discord.com':               '#5865F2',\n  'twitter.com':               '#1DA1F2',\n  'x.com':                     '#000000',\n  'instagram.com':             '#E1306C',\n  'reddit.com':                '#FF4500',\n  'spotify.com':               '#1DB954',\n  'netflix.com':               '#E50914',\n  'trello.com':                '#0052CC',\n  'slack.com':                 '#4A154B',\n  'linkedin.com':              '#0A66C2',\n  'amazon.com':                '#FF9900',\n  'wikipedia.org':             '#636466',\n  'stackoverflow.com':         '#F58025',\n};\n\nfunction getBrandColor(url) {\n  try {\n    const host = new URL(url).hostname.replace('www.','');\n    for (const [domain, color] of Object.entries(BRAND_COLORS)) {\n      if (host === domain || host.endsWith('.' + domain)) return color;\n    }\n  } catch {}\n  return null;\n}\n\n// Convert hex color to rgba components\nfunction hexToRgb(hex) {\n  const m = hex.replace('#','').match(/.{2}/g);\n  if (!m) return null;\n  return { r: parseInt(m[0],16), g: parseInt(m[1],16), b: parseInt(m[2],16) };\n}\n\n// ── Site Card ────────────────────────────────\nfunction buildSiteCard(site) {\n  const div = document.createElement('div');\n  div.className = 'site-card';\n  div.dataset.siteId = site.id;\n  div.draggable = true;\n\n  const wrapId = 'iw_' + site.id;\n\n  // Priority: 1) custom img  2) clearbit logo  3) google favicon  4) fallback letter\n  const hostname = (() => { try { return new URL(site.url).hostname; } catch { return ''; } })();\n  const clearbit  = hostname ? `https://logo.clearbit.com/${hostname}` : '';\n  const gfavicon  = site.url ? getFavicon(site.url) : '';\n  const imgSrc    = site.img || clearbit || gfavicon;\n  const initial   = (site.name || '?')[0].toUpperCase();\n\n  // Pre-apply brand color to wrap\n  const brandColor = getBrandColor(site.url || '');\n  const rgb = brandColor ? hexToRgb(brandColor) : null;\n  const wrapStyle = rgb\n    ? `background:rgba(${rgb.r},${rgb.g},${rgb.b},0.18);box-shadow:0 2px 10px rgba(${rgb.r},${rgb.g},${rgb.b},0.3);`\n    : '';\n\n  div.innerHTML = `\n    <div class=\"site-card-hover-overlay\"></div>\n    <div class=\"site-icon-wrap\" id=\"${wrapId}\" style=\"${wrapStyle}\">\n      ${imgSrc\n        ? `<img src=\"${escHtml(imgSrc)}\" alt=\"${escHtml(site.name)}\" loading=\"lazy\"\n             onerror=\"siteImgFallback(this,'${escHtml(gfavicon)}','${initial}','${wrapId}')\">`\n        : `<div class=\"site-favicon-fallback\">${initial}</div>`}\n    </div>\n    <span class=\"site-name\">${escHtml(site.name)}</span>\n    ${site.desc ? `<div class=\"site-tooltip\">${escHtml(site.desc)}</div>` : ''}\n    <div class=\"site-edit-overlay\">\n      <button onclick=\"editSite('${site.id}',event)\" title=\"Modifier\">✏️</button>\n      <button class=\"del-btn\" onclick=\"deleteSite('${site.id}',event)\" title=\"Supprimer\">🗑️</button>\n    </div>\n  `;\n\n  div.addEventListener('click', e => {\n    if (!e.target.closest('.site-edit-overlay') && !editMode) {\n      let url = site.url;\n      if (url && url !== '#') window.open(url, '_blank', 'noopener');\n    }\n  });\n\n  div.addEventListener('dragstart', e => onSiteDragStart(e, site.id, div));\n  div.addEventListener('dragend',   onSiteDragEnd);\n  return div;\n}\n\n// Cascade fallback: clearbit → google favicon → letter\nfunction siteImgFallback(img, googleFavicon, initial, wrapId) {\n  // If clearbit failed, try google favicon\n  if (googleFavicon && img.src !== googleFavicon && !img.src.includes('google.com/s2')) {\n    img.src = googleFavicon;\n    return;\n  }\n  // Both failed → show letter fallback\n  img.style.display = 'none';\n  const wrap = document.getElementById(wrapId);\n  if (wrap) {\n    let fb = wrap.querySelector('.site-favicon-fallback');\n    if (!fb) {\n      fb = document.createElement('div');\n      fb.className = 'site-favicon-fallback';\n      fb.textContent = initial;\n      wrap.appendChild(fb);\n    }\n    fb.style.display = 'flex';\n  }\n}\n\n\n// ── Personal Card — same size as site-card ────\nfunction buildPersonalCard(site) {\n  const div = document.createElement('div');\n  // Reuse site-card class for same size/layout, add personal-card for specific styles\n  div.className = 'site-card personal-card';\n  div.dataset.siteId = site.id;\n  div.draggable = true;\n\n  const color = site.color || 'var(--accent)';\n  const wrapId = 'iw_p_' + site.id;\n\n  // Build icon: use img if set, else colored initial\n  const imgSrc = site.img || '';\n  const initial = (site.name || '?')[0].toUpperCase();\n  const rgb = hexToRgb(color.startsWith('#') ? color : '#6c8eff');\n\n  div.innerHTML = `\n    <div class=\"site-card-hover-overlay\"></div>\n    <div class=\"site-icon-wrap\" id=\"${wrapId}\"\n         style=\"background:rgba(${rgb.r},${rgb.g},${rgb.b},0.22)\">\n      ${imgSrc\n        ? `<img src=\"${escHtml(imgSrc)}\" alt=\"${escHtml(site.name)}\" loading=\"lazy\"\n             onerror=\"this.style.display='none';this.nextElementSibling.style.display='flex'\">`\n        : ''}\n      <div class=\"site-favicon-fallback\" style=\"${imgSrc?'display:none':'display:flex'};background:${color};color:#fff\">${initial}</div>\n    </div>\n    <span class=\"site-name\">${escHtml(site.name)}</span>\n    ${site.desc ? `<div class=\"site-tooltip\">${escHtml(site.desc)}</div>` : ''}\n    <div class=\"personal-card-hover\">\n      <span class=\"personal-card-hover-name\">${escHtml(site.name)}</span>\n    </div>\n    <div class=\"site-edit-overlay\">\n      <button onclick=\"editSite('${site.id}',event)\" title=\"Modifier\">✏️</button>\n      <button class=\"del-btn\" onclick=\"deleteSite('${site.id}',event)\" title=\"Supprimer\">🗑️</button>\n    </div>\n  `;\n\n  div.addEventListener('click', e => {\n    if (!e.target.closest('.site-edit-overlay') && !e.target.closest('.personal-card-hover') && !editMode) {\n      let url = site.url;\n      if (!url || url === '#') return;\n      if (!url.match(/^https?:\\/\\//i) && !url.match(/^file:\\/\\//i)) url = 'https://' + url;\n      window.open(url, '_blank', 'noopener');\n    }\n  });\n\n  div.addEventListener('dragstart', e => onSiteDragStart(e, site.id, div));\n  div.addEventListener('dragend',   onSiteDragEnd);\n  return div;\n}\n\n// ── Drag & Drop (sites between sections) ─────\nfunction onSiteDragStart(e, siteId, el) {\n  dragSite = siteId;\n  e.dataTransfer.effectAllowed = 'move';\n  e.dataTransfer.setData('text/plain', siteId);\n\n  // Custom ghost\n  const rect = el.getBoundingClientRect();\n  dragGhost = el.cloneNode(true);\n  dragGhost.style.cssText = `\n    position:fixed; top:-9999px; left:-9999px;\n    width:${rect.width}px; opacity:0.85; pointer-events:none;\n    transform:rotate(3deg) scale(1.05);\n    border-radius:var(--r);\n    box-shadow:0 12px 40px rgba(0,0,0,0.5);\n    z-index:9999;\n    transition:none;\n  `;\n  document.body.appendChild(dragGhost);\n  e.dataTransfer.setDragImage(dragGhost, rect.width/2, rect.height/2);\n\n  setTimeout(() => {\n    el.style.opacity = '0.35';\n    el.style.transform = 'scale(0.95)';\n  }, 0);\n}\n\nfunction onSiteDragEnd(e) {\n  this.style.opacity = '';\n  this.style.transform = '';\n  if (dragGhost) { dragGhost.remove(); dragGhost = null; }\n  dragSite = null;\n  document.querySelectorAll('.sites-grid, .personal-grid').forEach(g => {\n    g.classList.remove('drag-over-grid');\n    g.querySelectorAll('.drop-indicator').forEach(d => d.remove());\n  });\n}\n\nfunction onGridDragOver(e) {\n  if (!dragSite) return;\n  e.preventDefault();\n  e.dataTransfer.dropEffect = 'move';\n  this.classList.add('drag-over-grid');\n\n  // Drop indicator line\n  const afterEl = getDragAfterElement(this, e.clientX, e.clientY);\n  const indicator = this.querySelector('.drop-indicator') || (() => {\n    const d = document.createElement('div');\n    d.className = 'drop-indicator';\n    return d;\n  })();\n  if (afterEl) this.insertBefore(indicator, afterEl);\n  else this.appendChild(indicator);\n}\n\nfunction onGridDragLeave(e) {\n  if (!this.contains(e.relatedTarget)) {\n    this.classList.remove('drag-over-grid');\n    this.querySelectorAll('.drop-indicator').forEach(d => d.remove());\n  }\n}\n\nfunction onGridDrop(e, targetSectionId) {\n  e.preventDefault();\n  if (!dragSite) return;\n  this.classList.remove('drag-over-grid');\n  this.querySelectorAll('.drop-indicator').forEach(d => d.remove());\n\n  const site = S.sites.find(s => s.id === dragSite);\n  if (!site) return;\n\n  // Remove from old position\n  S.sites = S.sites.filter(s => s.id !== dragSite);\n\n  // Find drop position\n  const afterEl = getDragAfterElement(this, e.clientX, e.clientY);\n  const afterId = afterEl?.dataset?.siteId;\n\n  // Update section\n  site.section = targetSectionId;\n\n  if (afterId) {\n    const afterIdx = S.sites.findIndex(s => s.id === afterId);\n    S.sites.splice(afterIdx, 0, site);\n  } else {\n    // Insert before add button = at end of this section\n    const sectionSites = S.sites.filter(s => s.section === targetSectionId);\n    const lastIdx = sectionSites.length ? S.sites.lastIndexOf(sectionSites[sectionSites.length-1]) + 1 : S.sites.length;\n    S.sites.splice(lastIdx, 0, site);\n  }\n\n  saveState();\n  renderAllSections();\n  initSearch();\n}\n\nfunction getDragAfterElement(container, x, y) {\n  // 2D grid: find nearest card center using combined X+Y distance\n  const cards = [...container.querySelectorAll('.site-card, .personal-card')]\n    .filter(el => el.dataset.siteId && el.dataset.siteId !== dragSite);\n\n  if (!cards.length) return null;\n\n  let best = null, bestScore = Infinity;\n\n  cards.forEach(card => {\n    const box = card.getBoundingClientRect();\n    const cx  = box.left + box.width  / 2;\n    const cy  = box.top  + box.height / 2;\n\n    // Use row-aware comparison:\n    // Cards in a row above → they come before\n    // Cards in the same row → use X to decide\n    const rowH = box.height;\n    const sameRow = Math.abs(y - cy) < rowH * 0.6;\n\n    let score;\n    if (sameRow) {\n      // Within same row: prefer cards to the right of cursor\n      score = x < cx ? (cx - x) : 10000 + (x - cx);\n    } else {\n      // Different row: prefer cards below cursor\n      score = y < cy ? 100000 + (cy - y) : Infinity;\n    }\n\n    if (score < bestScore) { bestScore = score; best = card; }\n  });\n\n  // If cursor is past the last card in all rows → return null (append)\n  if (bestScore === Infinity) return null;\n\n  // Check if we should insert before or after best\n  const box = best.getBoundingClientRect();\n  const cx  = box.left + box.width  / 2;\n  const cy  = box.top  + box.height / 2;\n  const sameRow = Math.abs(y - cy) < box.height * 0.6;\n\n  if (sameRow && x > cx) {\n    // Cursor is right of best center → insert after → return next sibling\n    const cards2 = [...container.querySelectorAll('.site-card, .personal-card')]\n      .filter(el => el.dataset.siteId && el.dataset.siteId !== dragSite);\n    const idx = cards2.indexOf(best);\n    return cards2[idx + 1] || null; // null = append\n  }\n\n  return best; // insert before best\n}\n\n// ── Edit Mode ─────────────────────────────────\nfunction toggleEditMode() {\n  editMode = !editMode;\n  document.body.classList.toggle('edit-mode', editMode);\n  document.getElementById('edit-mode-btn').classList.toggle('active', editMode);\n  updateEditBar();\n  toast(editMode ? '✏️ Mode édition activé' : '✓ Mode édition désactivé');\n}\n\nfunction updateEditBar() {\n  let bar = document.getElementById('edit-bar');\n  if (editMode) {\n    if (!bar) {\n      bar = document.createElement('div');\n      bar.id = 'edit-bar';\n      bar.innerHTML = `\n        <div class=\"edit-bar-inner\">\n          <span class=\"edit-bar-label\">Mode Édition</span>\n          <button class=\"edit-bar-add\" onclick=\"addSection()\">\n            <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\"><line x1=\"12\" y1=\"5\" x2=\"12\" y2=\"19\"/><line x1=\"5\" y1=\"12\" x2=\"19\" y2=\"12\"/></svg>\n            Nouvelle section\n          </button>\n          <button class=\"edit-bar-done\" onclick=\"toggleEditMode()\">Terminer ✓</button>\n        </div>`;\n      document.body.appendChild(bar);\n      requestAnimationFrame(() => bar.classList.add('open'));\n    }\n  } else {\n    if (bar) { bar.classList.remove('open'); setTimeout(() => bar.remove(), 300); }\n  }\n}\n\n// ── Modal ─────────────────────────────────────\nfunction openModal(sectionId, sectionType, siteId) {\n  modalCtx = { sectionId, sectionType, siteId };\n  document.getElementById('modal-title').textContent = siteId ? 'Modifier le site' : 'Ajouter un site';\n  document.getElementById('modal-img-preview').style.display = 'none';\n  window._pendingImgData = null;\n  populateModalSectionSelect(sectionId);\n\n  if (siteId) {\n    const site = S.sites.find(s => s.id === siteId);\n    if (site) {\n      document.getElementById('modal-name').value = site.name;\n      document.getElementById('modal-url').value = site.url;\n      document.getElementById('modal-desc').value = site.desc || '';\n      document.getElementById('modal-img').value = (!site.img || site.img.startsWith('data:')) ? '' : site.img;\n      document.getElementById('modal-section').value = site.section;\n      if (site.img) {\n        const p = document.getElementById('modal-img-preview');\n        p.src = site.img; p.style.display = 'block';\n      }\n    }\n  } else {\n    ['modal-name','modal-url','modal-desc','modal-img'].forEach(id => document.getElementById(id).value = '');\n    document.getElementById('modal-section').value = sectionId || '';\n  }\n  document.getElementById('modal-bg').classList.add('open');\n}\n\nfunction populateModalSectionSelect(currentId) {\n  const sel = document.getElementById('modal-section');\n  sel.innerHTML = '';\n  S.sections.forEach(sec => {\n    const o = new Option(sec.label, sec.id);\n    if (sec.id === currentId) o.selected = true;\n    sel.appendChild(o);\n  });\n}\n\nfunction closeModal() {\n  document.getElementById('modal-bg').classList.remove('open');\n  modalCtx = null;\n}\n\nfunction saveModal() {\n  const name    = document.getElementById('modal-name').value.trim();\n  const url     = document.getElementById('modal-url').value.trim();\n  const desc    = document.getElementById('modal-desc').value.trim();\n  const imgUrl  = document.getElementById('modal-img').value.trim();\n  const section = document.getElementById('modal-section').value;\n  if (!name) { toast('Le nom est requis'); return; }\n\n  const img = window._pendingImgData || imgUrl;\n  window._pendingImgData = null;\n\n  if (modalCtx?.siteId) {\n    const site = S.sites.find(s => s.id === modalCtx.siteId);\n    if (site) Object.assign(site, { name, url, desc, img, section });\n  } else {\n    S.sites.push({ id: genId(), name, url, desc, img, section, color: S.accent });\n  }\n\n  saveState(); closeModal(); renderAllSections(); initSearch();\n  toast('Site enregistré ✓');\n}\n\nfunction editSite(siteId, e) {\n  e?.preventDefault(); e?.stopPropagation();\n  const site = S.sites.find(s => s.id === siteId);\n  if (site) openModal(site.section, null, siteId);\n}\n\nfunction deleteSite(siteId, e) {\n  e?.preventDefault(); e?.stopPropagation();\n  if (!confirm('Supprimer ce site ?')) return;\n  S.sites = S.sites.filter(s => s.id !== siteId);\n  saveState(); renderAllSections(); initSearch();\n  toast('Site supprimé');\n}\n\nfunction loadSiteImg(input) {\n  const file = input.files[0]; if (!file) return;\n  const reader = new FileReader();\n  reader.onload = ev => {\n    window._pendingImgData = ev.target.result;\n    const p = document.getElementById('modal-img-preview');\n    p.src = ev.target.result; p.style.display = 'block';\n    document.getElementById('modal-img').value = '';\n  };\n  reader.readAsDataURL(file);\n}\n\n// ── Sections ──────────────────────────────────\nfunction addSection() {\n  document.getElementById('sec-modal-bg').classList.add('open');\n  setTimeout(() => document.getElementById('sec-modal-name').focus(), 100);\n}\nfunction closeSecModal(e) {\n  if (!e || e.target === document.getElementById('sec-modal-bg'))\n    document.getElementById('sec-modal-bg').classList.remove('open');\n}\nfunction saveSecModal() {\n  const name = document.getElementById('sec-modal-name').value.trim();\n  if (!name) return;\n  S.sections.push({ id: 'sec_' + Date.now(), label: name, type: 'general' });\n  saveState();\n  document.getElementById('sec-modal-bg').classList.remove('open');\n  document.getElementById('sec-modal-name').value = '';\n  renderAllSections();\n  toast(`Section \"${name}\" créée`);\n}\nfunction deleteSection(id) {\n  const count = S.sites.filter(s => s.section === id).length;\n  if (count > 0 && !confirm(`Cette section contient ${count} site(s). Supprimer quand même ?`)) return;\n  S.sites = S.sites.filter(s => s.section !== id);\n  S.sections = S.sections.filter(s => s.id !== id);\n  saveState(); renderAllSections();\n  toast('Section supprimée');\n}\nfunction renderSectionManager() {\n  const wrap = document.getElementById('section-manager'); if (!wrap) return;\n  wrap.innerHTML = '';\n  S.sections.forEach(sec => {\n    const row = document.createElement('div');\n    row.className = 'section-mgr-item';\n    row.innerHTML = `<span>${escHtml(sec.label)}</span><button onclick=\"deleteSection('${sec.id}')\">×</button>`;\n    wrap.appendChild(row);\n  });\n}\n\ndocument.addEventListener('DOMContentLoaded', () => {\n  const mbg = document.getElementById('modal-bg');\n  if (mbg) mbg.addEventListener('click', e => { if(e.target===mbg) closeModal(); });\n  const sbg = document.getElementById('sec-modal-bg');\n  if (sbg) sbg.addEventListener('click', closeSecModal);\n  const sname = document.getElementById('sec-modal-name');\n  if (sname) sname.addEventListener('keydown', e => { if(e.key==='Enter') saveSecModal(); });\n  const imgInp = document.getElementById('modal-img');\n  if (imgInp) imgInp.addEventListener('input', () => {\n    const v = imgInp.value.trim();\n    const p = document.getElementById('modal-img-preview');\n    if (v) { p.src = v; p.style.display = 'block'; } else p.style.display = 'none';\n  });\n});\n\n/* ══════════════════════════════════════\n   SEARCH.JS — Fuzzy search + Google fallback\n══════════════════════════════════════ */\n\nfunction initSearch() {\n  const inp = document.getElementById('search-input');\n  const res = document.getElementById('search-results');\n  if (!inp) return;\n\n  inp.addEventListener('input', onSearch);\n  inp.addEventListener('focus', () => { if (inp.value.trim()) onSearch(); });\n  inp.addEventListener('keydown', e => {\n    if (e.key === 'Escape') { res.classList.remove('open'); inp.blur(); return; }\n    if (e.key === 'Enter') {\n      // If no results or empty → Google search\n      const q = inp.value.trim();\n      if (q) {\n        const firstLink = res.querySelector('.sr-item');\n        if (firstLink && res.classList.contains('open')) {\n          firstLink.click();\n        } else {\n          window.open('https://www.google.com/search?q=' + encodeURIComponent(q), '_blank');\n        }\n        res.classList.remove('open');\n        inp.value = '';\n      }\n    }\n  });\n\n  document.addEventListener('click', e => {\n    if (!e.target.closest('#search-wrap')) res.classList.remove('open');\n  });\n}\n\nfunction fuzzyScore(query, text) {\n  if (!text) return 0;\n  query = query.toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g,'');\n  text  = text.toLowerCase().normalize('NFD').replace(/[\\u0300-\\u036f]/g,'');\n  if (text === query)        return 200;\n  if (text.startsWith(query))return 150;\n  if (text.includes(query))  return 100;\n  let score = 0, qi = 0, consec = 0;\n  for (let i = 0; i < text.length && qi < query.length; i++) {\n    if (text[i] === query[qi]) { qi++; consec++; score += consec * 2; }\n    else { consec = 0; }\n  }\n  return qi === query.length ? score : 0;\n}\n\nfunction onSearch() {\n  const inp = document.getElementById('search-input');\n  const res = document.getElementById('search-results');\n  const q = inp.value.trim();\n  if (!q) { res.classList.remove('open'); return; }\n\n  const scored = S.sites\n    .map(site => {\n      const sec = S.sections.find(s => s.id === site.section);\n      const ns = fuzzyScore(q, site.name) * 2;\n      const ds = fuzzyScore(q, site.desc);\n      const us = fuzzyScore(q, site.url) * 0.5;\n      return { ...site, _score: ns+ds+us, _secLabel: sec?.label||'' };\n    })\n    .filter(s => s._score > 0)\n    .sort((a,b) => b._score - a._score)\n    .slice(0, 7);\n\n  res.innerHTML = '';\n\n  if (scored.length) {\n    scored.forEach(s => {\n      const imgSrc = s.img || getFavicon(s.url);\n      const initial = (s.name||'?')[0].toUpperCase();\n      const a = document.createElement('a');\n      a.className = 'sr-item';\n      a.href = s.url; a.target = '_blank'; a.rel = 'noopener';\n      a.innerHTML = `\n        ${imgSrc\n          ? `<img src=\"${escHtml(imgSrc)}\" alt=\"\" onerror=\"this.style.display='none'\">`\n          : `<div class=\"sr-fallback\">${initial}</div>`}\n        <div>\n          <div class=\"sn\">${escHtml(s.name)}</div>\n          <div class=\"sc\">${escHtml(s._secLabel)}${s.desc?' · '+escHtml(s.desc):''}</div>\n        </div>`;\n      res.appendChild(a);\n    });\n  }\n\n  // Always add Google search option at bottom\n  const gLink = document.createElement('a');\n  gLink.className = 'sr-item sr-google';\n  gLink.href = 'https://www.google.com/search?q=' + encodeURIComponent(q);\n  gLink.target = '_blank'; gLink.rel = 'noopener';\n  gLink.innerHTML = `\n    <div class=\"sr-google-icon\">G</div>\n    <div>\n      <div class=\"sn\">Rechercher \"<strong>${escHtml(q)}</strong>\" sur Google</div>\n      <div class=\"sc\">google.com</div>\n    </div>`;\n  res.appendChild(gLink);\n\n  res.classList.add('open');\n}\n\n/* ══════════════════════════════════════\n   TRANSLATE.JS — MyMemory free API\n══════════════════════════════════════ */\n\nconst TRANSLATE_LANGS = [\n  ['fr', '🇫🇷 Français'],\n  ['en', '🇬🇧 English'],\n  ['zh', '🇨🇳 中文'],\n  ['ja', '🇯🇵 日本語'],\n  ['es', '🇪🇸 Español'],\n  ['de', '🇩🇪 Deutsch'],\n  ['it', '🇮🇹 Italiano'],\n  ['pt', '🇵🇹 Português'],\n  ['ar', '🇸🇦 العربية'],\n  ['ko', '🇰🇷 한국어'],\n  ['ru', '🇷🇺 Русский'],\n];\n\nlet tlFrom = 'fr', tlTo = 'en';\n\nfunction initTranslate() {\n  populateLangSelects();\n}\n\nfunction populateLangSelects() {\n  const fromSel = document.getElementById('tl-from');\n  const toSel   = document.getElementById('tl-to');\n  if (!fromSel) return;\n\n  fromSel.innerHTML = '';\n  toSel.innerHTML   = '';\n\n  TRANSLATE_LANGS.forEach(([code, label]) => {\n    const o1 = new Option(label, code);\n    const o2 = new Option(label, code);\n    if (code === tlFrom) o1.selected = true;\n    if (code === tlTo)   o2.selected = true;\n    fromSel.appendChild(o1);\n    toSel.appendChild(o2);\n  });\n\n  fromSel.onchange = () => { tlFrom = fromSel.value; };\n  toSel.onchange   = () => { tlTo   = toSel.value;   };\n}\n\nfunction swapLangs() {\n  [tlFrom, tlTo] = [tlTo, tlFrom];\n  populateLangSelects();\n\n  // Also swap text\n  const input  = document.getElementById('tl-input');\n  const output = document.getElementById('tl-output');\n  const outText = output.dataset.rawText;\n  if (outText) {\n    input.value = outText;\n    output.innerHTML = '<span class=\"tl-placeholder\">La traduction apparaîtra ici</span>';\n    output.dataset.rawText = '';\n  }\n}\n\nasync function doTranslate() {\n  const input = document.getElementById('tl-input');\n  const output = document.getElementById('tl-output');\n  const text = input.value.trim();\n  if (!text) return;\n\n  output.innerHTML = '<span class=\"tl-placeholder\">Traduction en cours…</span>';\n\n  try {\n    const langPair = `${tlFrom}|${tlTo}`;\n    const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=${langPair}`;\n    const res = await fetch(url);\n    const data = await res.json();\n\n    if (data.responseStatus === 200) {\n      const translated = data.responseData.translatedText;\n      output.textContent = translated;\n      output.dataset.rawText = translated;\n    } else {\n      output.innerHTML = '<span class=\"tl-placeholder\">Erreur de traduction. Réessayez.</span>';\n    }\n  } catch (e) {\n    output.innerHTML = '<span class=\"tl-placeholder\">Erreur réseau. Vérifiez votre connexion.</span>';\n  }\n}\n\nfunction copyTranslation() {\n  const output = document.getElementById('tl-output');\n  const text = output.dataset.rawText || output.textContent;\n  if (!text || output.querySelector('.tl-placeholder')) return;\n  navigator.clipboard.writeText(text).then(() => toast('Copié dans le presse-papier'));\n}\n\ndocument.addEventListener('DOMContentLoaded', () => {\n  const inp = document.getElementById('tl-input');\n  if (inp) {\n    inp.addEventListener('keydown', e => {\n      if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) doTranslate();\n    });\n  }\n});\n\n/* ══════════════════════════════════════\n   CHAT.JS — LM Studio + Anthropic API\n══════════════════════════════════════ */\n\nlet chatOpen = false;\nlet chatLoading = false;\n\nfunction toggleChat() {\n  chatOpen = !chatOpen;\n  document.getElementById('chat-panel').classList.toggle('open', chatOpen);\n  document.getElementById('chat-bubble').classList.toggle('open', chatOpen);\n  if (chatOpen) setTimeout(() => document.getElementById('chat-input')?.focus(), 200);\n}\n\nfunction clearChat() {\n  S.chatHistory = []; saveState();\n  document.getElementById('chat-messages').innerHTML = `\n    <div class=\"chat-msg assistant\">\n      <div class=\"chat-bubble-msg\">Bonjour ! Comment puis-je vous aider ?</div>\n    </div>`;\n}\n\n// ── Send message ──────────────────────────────\nasync function sendChatMsg() {\n  if (chatLoading) return;\n  const input = document.getElementById('chat-input');\n  const text = input.value.trim();\n\n  // Collect attached files\n  const attachments = window._chatAttachments || [];\n  if (!text && !attachments.length) return;\n\n  input.value = '';\n  autoResizeChatInput(input);\n\n  // Build content for display\n  let displayContent = text;\n  if (attachments.length) displayContent += attachments.map(a => `\\n📎 ${a.name}`).join('');\n  appendChatMsg('user', displayContent);\n\n  // Build API content\n  let msgContent = [];\n  for (const att of attachments) {\n    if (att.type.startsWith('image/')) {\n      msgContent.push({ type:'image', source:{ type:'base64', media_type: att.type, data: att.data } });\n    } else {\n      msgContent.push({ type:'text', text:`[Fichier: ${att.name}]\\n${att.textContent||''}` });\n    }\n  }\n  if (text) msgContent.push({ type:'text', text });\n  if (msgContent.length === 1 && msgContent[0].type === 'text') msgContent = msgContent[0].text;\n\n  S.chatHistory.push({ role:'user', content: msgContent });\n  window._chatAttachments = [];\n  renderAttachmentPreviews();\n\n  chatLoading = true;\n  document.getElementById('chat-send').disabled = true;\n  const typing = appendTyping();\n\n  try {\n    const backend = document.getElementById('chat-backend')?.value || 'anthropic';\n\n    let reply;\n    if (backend === 'lmstudio') {\n      reply = await callLMStudio();\n    } else {\n      reply = await callAnthropic();\n    }\n\n    typing.remove();\n    appendChatMsg('assistant', reply);\n    S.chatHistory.push({ role:'assistant', content: reply });\n    if (S.chatHistory.length > 40) S.chatHistory = S.chatHistory.slice(-40);\n    saveState();\n\n  } catch (err) {\n    typing.remove();\n    appendChatMsg('assistant', `⚠️ Erreur : ${err.message}`);\n  }\n\n  chatLoading = false;\n  document.getElementById('chat-send').disabled = false;\n}\n\nasync function callAnthropic() {\n  const messages = S.chatHistory.map(m => ({ role:m.role, content:m.content }));\n  const res = await fetch('https://api.anthropic.com/v1/messages', {\n    method:'POST',\n    headers:{ 'Content-Type':'application/json' },\n    body: JSON.stringify({\n      model: 'claude-sonnet-4-20250514',\n      max_tokens: 1000,\n      system: `Tu es un assistant personnel. Réponds en ${S.lang==='fr'?'français':S.lang==='zh'?'chinois':'anglais'}. Sois concis.`,\n      messages\n    })\n  });\n  if (!res.ok) { const e = await res.json().catch(()=>({})); throw new Error(e.error?.message||`HTTP ${res.status}`); }\n  const d = await res.json();\n  return d.content?.find(b=>b.type==='text')?.text || '…';\n}\n\nasync function callLMStudio() {\n  let host = (document.getElementById('lms-host')?.value || 'http://localhost:1234').replace(/\\/$/, '');\n  const model = document.getElementById('lms-model')?.value || '';\n\n  // LM Studio expose OpenAI-compatible endpoint at /v1\n  // Some builds use /api/v1 — we try both\n  const messages = [\n    { role:'system', content:`Tu es un assistant personnel. Réponds en ${S.lang==='fr'?'français':S.lang==='zh'?'chinois':'anglais'}.` },\n    ...S.chatHistory.map(m => ({\n      role: m.role,\n      content: typeof m.content === 'string' ? m.content : m.content.filter(b=>b.type==='text').map(b=>b.text).join('\\n')\n    }))\n  ];\n  const body = { messages, temperature:0.7, max_tokens:1000, stream:false };\n  if (model) body.model = model;\n\n  // Determine base path: if user included /api/v1 or /v1, use as-is; else append /v1\n  let basePath = host;\n  if (!basePath.match(/\\/v1\\/?$/) && !basePath.match(/\\/api\\/v1\\/?$/)) {\n    basePath = host + '/v1';\n  }\n\n  const res = await fetch(`${basePath}/chat/completions`, {\n    method:'POST',\n    headers:{ 'Content-Type':'application/json' },\n    body: JSON.stringify(body)\n  });\n\n  if (!res.ok) {\n    let msg = `LM Studio HTTP ${res.status}`;\n    if (res.status === 0 || res.type === 'opaque') msg += ' — CORS bloqué. Dans LM Studio: Préférences → Serveur → Activer CORS.';\n    throw new Error(msg);\n  }\n  const d = await res.json();\n  return d.choices?.[0]?.message?.content || '…';\n}\n\n// ── File attachments ──────────────────────────\nwindow._chatAttachments = [];\n\nfunction handleChatFileAttach(input) {\n  const files = [...input.files];\n  files.forEach(file => {\n    const reader = new FileReader();\n    reader.onload = e => {\n      const data = e.target.result.split(',')[1]; // base64\n      if (file.type.startsWith('image/')) {\n        window._chatAttachments.push({ name:file.name, type:file.type, data });\n      } else if (file.type === 'application/pdf' || file.type.startsWith('text/')) {\n        // For text files, read as text\n        const fr = new FileReader();\n        fr.onload = ev => {\n          window._chatAttachments.push({ name:file.name, type:file.type, data, textContent:ev.target.result });\n          renderAttachmentPreviews();\n        };\n        fr.readAsText(file);\n        return;\n      } else {\n        window._chatAttachments.push({ name:file.name, type:file.type, data });\n      }\n      renderAttachmentPreviews();\n    };\n    reader.readAsDataURL(file);\n  });\n  input.value = '';\n}\n\nfunction renderAttachmentPreviews() {\n  let bar = document.getElementById('chat-attach-bar');\n  const atts = window._chatAttachments || [];\n  if (!atts.length) { bar?.remove(); return; }\n  if (!bar) {\n    bar = document.createElement('div');\n    bar.id = 'chat-attach-bar';\n    document.getElementById('chat-input-row').insertAdjacentElement('beforebegin', bar);\n  }\n  bar.innerHTML = atts.map((a,i) => `\n    <div class=\"chat-attach-item\">\n      ${a.type.startsWith('image/')\n        ? `<img src=\"data:${a.type};base64,${a.data}\" alt=\"${escHtml(a.name)}\">`\n        : `<span>📎</span>`}\n      <span class=\"chat-attach-name\">${escHtml(a.name)}</span>\n      <button onclick=\"removeAttachment(${i})\">×</button>\n    </div>`).join('');\n}\n\nfunction removeAttachment(i) {\n  window._chatAttachments.splice(i,1);\n  renderAttachmentPreviews();\n}\n\n// ── UI Helpers ────────────────────────────────\nfunction appendChatMsg(role, text) {\n  const msgs = document.getElementById('chat-messages');\n  const div = document.createElement('div');\n  div.className = `chat-msg ${role}`;\n  const html = String(text)\n    .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')\n    .replace(/\\*\\*(.*?)\\*\\*/g,'<strong>$1</strong>')\n    .replace(/\\*(.*?)\\*/g,'<em>$1</em>')\n    .replace(/`([^`]+)`/g,'<code>$1</code>')\n    .replace(/\\n/g,'<br>');\n  div.innerHTML = `<div class=\"chat-bubble-msg\">${html}</div>`;\n  msgs.appendChild(div);\n  msgs.scrollTop = msgs.scrollHeight;\n  return div;\n}\nfunction appendTyping() {\n  const msgs = document.getElementById('chat-messages');\n  const div = document.createElement('div');\n  div.className = 'chat-msg assistant chat-typing';\n  div.innerHTML = `<div class=\"chat-bubble-msg\"><div class=\"dot\"></div><div class=\"dot\"></div><div class=\"dot\"></div></div>`;\n  msgs.appendChild(div);\n  msgs.scrollTop = msgs.scrollHeight;\n  return div;\n}\nfunction autoResizeChatInput(el) {\n  el.style.height = 'auto';\n  el.style.height = Math.min(el.scrollHeight, 120) + 'px';\n}\n\n// ── LM Studio: fetch available models ─────────\nasync function fetchLMStudioModels() {\n  let host = (document.getElementById('lms-host')?.value || 'http://localhost:1234').replace(/\\/$/, '');\n  const sel = document.getElementById('lms-model');\n\n  // Auto-detect correct path\n  let basePath = host;\n  if (!basePath.match(/\\/v1\\/?$/) && !basePath.match(/\\/api\\/v1\\/?$/)) {\n    basePath = host + '/v1';\n  }\n\n  try {\n    const res = await fetch(`${basePath}/models`);\n    if (!res.ok) throw new Error(`HTTP ${res.status}`);\n    const d = await res.json();\n    const models = d.data || [];\n    sel.innerHTML = models.length\n      ? models.map(m => `<option value=\"${m.id}\">${m.id}</option>`).join('')\n      : '<option value=\"\">Aucun modèle chargé</option>';\n    toast(`✓ ${models.length} modèle(s) trouvé(s)`);\n  } catch(e) {\n    sel.innerHTML = '<option value=\"\">Erreur de connexion</option>';\n    toast('⚠ LM Studio inaccessible — activez CORS dans Préférences → Serveur');\n  }\n}\n\ndocument.addEventListener('DOMContentLoaded', () => {\n  const inp = document.getElementById('chat-input');\n  if (inp) {\n    inp.addEventListener('keydown', e => { if(e.key==='Enter' && !e.shiftKey) { e.preventDefault(); sendChatMsg(); } });\n    inp.addEventListener('input', () => autoResizeChatInput(inp));\n  }\n  // Backend toggle\n  const backendSel = document.getElementById('chat-backend');\n  if (backendSel) backendSel.addEventListener('change', () => {\n    const isLMS = backendSel.value === 'lmstudio';\n    document.getElementById('lms-config').style.display = isLMS ? 'flex' : 'none';\n  });\n  // Restore history\n  if (S.chatHistory?.length) {\n    const msgs = document.getElementById('chat-messages');\n    msgs.innerHTML = `<div class=\"chat-msg assistant\"><div class=\"chat-bubble-msg\">Bonjour ! Comment puis-je vous aider ?</div></div>`;\n    S.chatHistory.forEach(m => appendChatMsg(m.role, typeof m.content==='string'?m.content:m.content.filter(b=>b.type==='text').map(b=>b.text).join('\\n')));\n  }\n});\n\n/* ══════════════════════════════════════\n   NOTIFICATIONS.JS\n══════════════════════════════════════ */\n\nfunction initNotifications() {\n  renderNotifications();\n\n  // Click outside to close\n  document.addEventListener('click', e => {\n    if (!e.target.closest('.notif-wrap')) {\n      document.getElementById('notif-panel')?.classList.remove('open');\n    }\n  });\n\n  document.getElementById('notif-btn')?.addEventListener('click', toggleNotifPanel);\n\n  // Demo: add a welcome notif if first time\n  if (!S.notifications.length) {\n    addNotification({ title: 'Bienvenue sur votre Dashboard !', from: 'Système', time: Date.now() });\n  }\n}\n\nfunction toggleNotifPanel() {\n  document.getElementById('notif-panel').classList.toggle('open');\n}\n\nfunction addNotification(notif) {\n  S.notifications.unshift({ id: genId(), ...notif });\n  if (S.notifications.length > 50) S.notifications = S.notifications.slice(0, 50);\n  saveState();\n  renderNotifications();\n}\n\nfunction deleteNotif(id) {\n  S.notifications = S.notifications.filter(n => n.id !== id);\n  saveState(); renderNotifications();\n}\n\nfunction clearNotifs() {\n  S.notifications = [];\n  saveState(); renderNotifications();\n}\n\nfunction renderNotifications() {\n  const list = document.getElementById('notif-list');\n  const badge = document.getElementById('notif-badge');\n  if (!list) return;\n\n  const count = S.notifications.length;\n  if (badge) {\n    badge.style.display = count ? 'flex' : 'none';\n    badge.textContent = count > 9 ? '9+' : count;\n  }\n\n  if (!count) {\n    list.innerHTML = '<div class=\"notif-empty\">Aucune notification</div>';\n    return;\n  }\n\n  list.innerHTML = '';\n  S.notifications.forEach(n => {\n    const item = document.createElement('div');\n    item.className = 'notif-item';\n    const age = formatNotifAge(n.time);\n    item.innerHTML = `\n      <div class=\"notif-dot\"></div>\n      <div style=\"flex:1\">\n        <div class=\"notif-text\">${escHtml(n.title)}</div>\n        ${n.from ? `<div class=\"notif-time\">${escHtml(n.from)} · ${age}</div>` : `<div class=\"notif-time\">${age}</div>`}\n      </div>\n      <button class=\"notif-del\" onclick=\"deleteNotif('${n.id}')\">×</button>\n    `;\n    list.appendChild(item);\n  });\n}\n\nfunction formatNotifAge(ts) {\n  if (!ts) return '';\n  const diff = Date.now() - ts;\n  const mins = Math.floor(diff / 60000);\n  if (mins < 1) return \"À l'instant\";\n  if (mins < 60) return `Il y a ${mins} min`;\n  const hrs = Math.floor(mins / 60);\n  if (hrs < 24) return `Il y a ${hrs} h`;\n  return `Il y a ${Math.floor(hrs/24)} j`;\n}\n\n/* ══════════════════════════════════════\n   WEATHER.JS — Clock + Multi-city weather\n══════════════════════════════════════ */\n\nfunction initWeatherClock() {\n  renderClock();\n  setInterval(renderClock, 1000);\n  loadWeatherCities();\n  setInterval(loadWeatherCities, 600000);\n}\n\n// ── Clock ─────────────────────────────────────\nfunction renderClock() {\n  const el = document.getElementById('clock-display');\n  if (!el) return;\n  const now = new Date();\n  el.textContent = now.toLocaleTimeString('fr-FR', { hour:'2-digit', minute:'2-digit', second:'2-digit' });\n}\n\n// ── Cities from state ─────────────────────────\nfunction loadWeatherCities() {\n  const city1 = S.weatherCity1 || '';\n  const city2 = S.weatherCity2 || '';\n  fetchWeatherForSlot(1, city1);\n  if (city2) {\n    fetchWeatherForSlot(2, city2);\n    document.getElementById('weather-slot-2').style.display = 'flex';\n    document.getElementById('weather-divider').style.display = 'block';\n  } else {\n    document.getElementById('weather-slot-2').style.display = 'none';\n    document.getElementById('weather-divider').style.display = 'none';\n  }\n}\n\nasync function fetchWeatherForSlot(slot, cityName) {\n  const iconEl = document.getElementById(`weather-icon-${slot}`);\n  const tempEl = document.getElementById(`weather-temp-${slot}`);\n  const descEl = document.getElementById(`weather-desc-${slot}`);\n  const cityEl = document.getElementById(`weather-city-${slot}`);\n  if (!iconEl) return;\n\n  try {\n    let lat, lon, city;\n\n    if (cityName) {\n      // Geocode city name via Open-Meteo geocoding (no key)\n      const geo = await fetch(\n        `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(cityName)}&count=1&language=fr&format=json`\n      ).then(r => r.json());\n      const result = geo.results?.[0];\n      if (!result) throw new Error('Ville introuvable');\n      lat  = result.latitude;\n      lon  = result.longitude;\n      city = result.name + (result.country_code ? `, ${result.country_code}` : '');\n    } else {\n      // Auto-detect via IP\n      const loc = await fetch('https://ipapi.co/json/').then(r => r.json());\n      lat  = loc.latitude;\n      lon  = loc.longitude;\n      city = loc.city || '';\n      if (!lat) throw new Error('no location');\n    }\n\n    const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&current=temperature_2m,weather_code&timezone=auto`;\n    const wx  = await fetch(url).then(r => r.json());\n    const temp = Math.round(wx.current.temperature_2m);\n    const code = wx.current.weather_code;\n\n    iconEl.textContent = weatherIcon(code);\n    tempEl.textContent = `${temp}°C`;\n    descEl.textContent = weatherDesc(code);\n    cityEl.textContent = city;\n  } catch(e) {\n    iconEl.textContent = '🌡';\n    tempEl.textContent = '--°C';\n    descEl.textContent = slot === 1 ? 'Cliquer pour définir une ville' : '';\n    cityEl.textContent = '';\n  }\n}\n\n// ── Weather settings modal ─────────────────────\nfunction openWeatherSettings() {\n  const modal = document.getElementById('weather-modal');\n  if (!modal) return;\n  document.getElementById('wm-city1').value = S.weatherCity1 || '';\n  document.getElementById('wm-city2').value = S.weatherCity2 || '';\n  modal.classList.add('open');\n  // Focus city1 after animation\n  setTimeout(() => document.getElementById('wm-city1')?.focus(), 80);\n}\n\nfunction closeWeatherSettings() {\n  const modal = document.getElementById('weather-modal');\n  if (modal) modal.classList.remove('open');\n}\n\nfunction saveWeatherSettings() {\n  S.weatherCity1 = document.getElementById('wm-city1').value.trim();\n  S.weatherCity2 = document.getElementById('wm-city2').value.trim();\n  saveState();\n  closeWeatherSettings();\n  loadWeatherCities();\n}\n\n// Close modal on backdrop click\ndocument.addEventListener('DOMContentLoaded', () => {\n  // weather modal backdrop click handled inline via onclick\n  const c1 = document.getElementById('wm-city1');\n  const c2 = document.getElementById('wm-city2');\n  if (c1) c1.addEventListener('keydown', e => { if(e.key==='Enter') c2?.focus(); });\n  if (c2) c2.addEventListener('keydown', e => { if(e.key==='Enter') saveWeatherSettings(); });\n});\n\n// ── Icons / Descriptions ─────────────────────\nfunction weatherIcon(code) {\n  if (code === 0)  return '☀️';\n  if (code <= 2)   return '🌤️';\n  if (code <= 3)   return '☁️';\n  if (code <= 49)  return '🌫️';\n  if (code <= 67)  return '🌧️';\n  if (code <= 79)  return '🌨️';\n  if (code <= 84)  return '🌦️';\n  if (code <= 99)  return '⛈️';\n  return '🌩️';\n}\nfunction weatherDesc(code) {\n  const map = {\n    0:'Clair', 1:'Peu nuageux', 2:'Partiellement nuageux', 3:'Couvert',\n    45:'Brouillard', 48:'Brouillard givrant',\n    51:'Bruine légère', 53:'Bruine', 55:'Bruine dense',\n    61:'Pluie légère', 63:'Pluie', 65:'Pluie forte',\n    71:'Neige légère', 73:'Neige', 75:'Neige forte',\n    80:'Averses légères', 81:'Averses', 82:'Averses fortes',\n    95:'Orage', 96:'Orage + grêle', 99:'Orage violent'\n  };\n  return map[code] || '';\n}\n\n/* ══════════════════════════════════════\n   SYNC.JS — GitHub Gist synchronisation\n   Token stocké uniquement en localStorage,\n   jamais dans le code source.\n══════════════════════════════════════ */\n\nconst GIST_FILENAME = 'dashboard-data.json';\nconst SYNC_KEY      = 'dash_gist_token';\nconst GIST_ID_KEY   = 'dash_gist_id';\n\nlet _syncDebounce = null;\nlet _syncPending  = false;\n\n// ── Public API ────────────────────────────────\n\nfunction getSyncToken()  { return localStorage.getItem(SYNC_KEY)  || ''; }\nfunction getSyncGistId() { return localStorage.getItem(GIST_ID_KEY) || ''; }\n\nfunction setSyncToken(token) {\n  if (token) localStorage.setItem(SYNC_KEY, token);\n  else        localStorage.removeItem(SYNC_KEY);\n}\n\nfunction setSyncGistId(id) {\n  if (id) localStorage.setItem(GIST_ID_KEY, id);\n  else     localStorage.removeItem(GIST_ID_KEY);\n}\n\n// Call this after every saveState() to trigger a debounced cloud sync\nfunction scheduleSyncSave() {\n  if (!getSyncToken()) return;\n  clearTimeout(_syncDebounce);\n  _syncDebounce = setTimeout(syncSave, 1500); // wait 1.5s after last change\n}\n\n// ── Save to Gist ──────────────────────────────\nasync function syncSave() {\n  const token = getSyncToken();\n  if (!token) return;\n\n  const data = JSON.stringify(S, null, 2);\n  const gistId = getSyncGistId();\n\n  try {\n    updateSyncStatus('saving');\n    let response, json;\n\n    if (gistId) {\n      // Update existing gist\n      response = await fetch(`https://api.github.com/gists/${gistId}`, {\n        method: 'PATCH',\n        headers: {\n          'Authorization': `token ${token}`,\n          'Content-Type': 'application/json',\n          'Accept': 'application/vnd.github.v3+json'\n        },\n        body: JSON.stringify({\n          files: { [GIST_FILENAME]: { content: data } }\n        })\n      });\n    } else {\n      // Create new gist\n      response = await fetch('https://api.github.com/gists', {\n        method: 'POST',\n        headers: {\n          'Authorization': `token ${token}`,\n          'Content-Type': 'application/json',\n          'Accept': 'application/vnd.github.v3+json'\n        },\n        body: JSON.stringify({\n          description: 'Dashboard personal data — do not edit manually',\n          public: false,\n          files: { [GIST_FILENAME]: { content: data } }\n        })\n      });\n    }\n\n    if (!response.ok) {\n      const err = await response.json().catch(() => ({}));\n      throw new Error(err.message || `HTTP ${response.status}`);\n    }\n\n    json = await response.json();\n    setSyncGistId(json.id);\n    updateSyncStatus('ok');\n    return true;\n\n  } catch(e) {\n    console.warn('Gist sync save error:', e.message);\n    updateSyncStatus('error', e.message);\n    return false;\n  }\n}\n\n// ── Load from Gist ────────────────────────────\nasync function syncLoad() {\n  const token  = getSyncToken();\n  const gistId = getSyncGistId();\n  if (!token || !gistId) return false;\n\n  try {\n    updateSyncStatus('loading');\n    const response = await fetch(`https://api.github.com/gists/${gistId}`, {\n      headers: {\n        'Authorization': `token ${token}`,\n        'Accept': 'application/vnd.github.v3+json'\n      }\n    });\n\n    if (!response.ok) throw new Error(`HTTP ${response.status}`);\n\n    const json = await response.json();\n    const content = json.files?.[GIST_FILENAME]?.content;\n    if (!content) throw new Error('Fichier introuvable dans le Gist');\n\n    const remote = JSON.parse(content);\n\n    // Merge: keep credentials from local, take data from remote\n    const localCreds = { username: S.username, password: S.password };\n    S = deepMerge(remote, JSON.parse(JSON.stringify(DEFAULT)));\n    S.username = localCreds.username;\n    S.password = localCreds.password;\n    S._version = STATE_VERSION;\n\n    saveState(); // persist locally too\n    updateSyncStatus('ok');\n    return true;\n\n  } catch(e) {\n    console.warn('Gist sync load error:', e.message);\n    updateSyncStatus('error', e.message);\n    return false;\n  }\n}\n\n// ── Validate token ────────────────────────────\nasync function validateGistToken(token) {\n  try {\n    const res = await fetch('https://api.github.com/user', {\n      headers: {\n        'Authorization': `token ${token}`,\n        'Accept': 'application/vnd.github.v3+json'\n      }\n    });\n    if (!res.ok) return null;\n    const data = await res.json();\n    return data.login || null;\n  } catch { return null; }\n}\n\n// ── UI helpers ────────────────────────────────\nfunction updateSyncStatus(state, msg) {\n  const dot   = document.getElementById('sync-dot');\n  const label = document.getElementById('sync-label');\n  if (!dot || !label) return;\n\n  const states = {\n    idle:    { color: 'var(--text-f)',   text: 'Non configuré' },\n    loading: { color: 'var(--warn)',     text: 'Chargement…'   },\n    saving:  { color: 'var(--warn)',     text: 'Sauvegarde…'   },\n    ok:      { color: 'var(--accent3)',  text: 'Synchronisé ✓' },\n    error:   { color: 'var(--danger)',   text: msg || 'Erreur' },\n  };\n  const s = states[state] || states.idle;\n  dot.style.background   = s.color;\n  dot.style.boxShadow    = state === 'ok' ? `0 0 6px ${s.color}` : 'none';\n  label.textContent       = s.text;\n}\n\n// ── Save settings from UI ─────────────────────\nasync function saveGistSettings() {\n  const tokenInput = document.getElementById('gist-token-input');\n  const token = tokenInput?.value.trim();\n  const btn   = document.getElementById('gist-save-btn');\n\n  if (!token) {\n    // Clear sync\n    setSyncToken('');\n    setSyncGistId('');\n    updateSyncStatus('idle');\n    toast('Synchronisation désactivée');\n    renderSyncSection();\n    return;\n  }\n\n  if (btn) { btn.disabled = true; btn.textContent = 'Vérification…'; }\n\n  const username = await validateGistToken(token);\n  if (!username) {\n    toast('❌ Token invalide ou expiré');\n    if (btn) { btn.disabled = false; btn.textContent = 'Connecter'; }\n    return;\n  }\n\n  setSyncToken(token);\n  if (btn) { btn.textContent = 'Connexion…'; }\n\n  // Try to load existing gist first\n  const gistId = getSyncGistId();\n  if (gistId) {\n    const loaded = await syncLoad();\n    if (loaded) {\n      toast(`✓ Connecté en tant que ${username} — données chargées`);\n      if (typeof reRenderAll === 'function') reRenderAll();\n    } else {\n      // Gist ID invalid → reset and push current state\n      setSyncGistId('');\n      await syncSave();\n      toast(`✓ Connecté en tant que ${username} — nouveau Gist créé`);\n    }\n  } else {\n    await syncSave();\n    toast(`✓ Connecté en tant que ${username} — Gist créé`);\n  }\n  renderSyncSection();\n\n  if (btn) { btn.disabled = false; btn.textContent = 'Connecter'; }\n  renderSyncSection();\n}\n\nasync function disconnectGist() {\n  setSyncToken('');\n  setSyncGistId('');\n  updateSyncStatus('idle');\n  toast('Synchronisation déconnectée');\n  renderSyncSection();\n}\n\nasync function manualSyncSave() {\n  if (!getSyncToken()) { toast('Aucun token configuré'); return; }\n  const ok = await syncSave();\n  toast(ok ? '✓ Sauvegardé dans le Gist' : '❌ Échec de la sauvegarde');\n}\n\nasync function manualSyncLoad() {\n  if (!getSyncToken()) { toast('Aucun token configuré'); return; }\n  const ok = await syncLoad();\n  if (ok) {\n    toast('✓ Données chargées depuis le Gist');\n    if (typeof reRenderAll === 'function') reRenderAll();\n  } else {\n    toast('❌ Impossible de charger les données');\n  }\n}\n\n// ── Render sync section in settings ──────────\nfunction renderSyncSection() {\n  const wrap = document.getElementById('sync-section');\n  if (!wrap) return;\n\n  const token  = getSyncToken();\n  const gistId = getSyncGistId();\n  const hasToken = !!token;\n\n  wrap.innerHTML = `\n    <div style=\"display:flex;align-items:center;gap:8px;margin-bottom:10px\">\n      <div id=\"sync-dot\" style=\"width:8px;height:8px;border-radius:50%;background:${hasToken?'var(--accent3)':'var(--text-f)'};transition:all .3s;flex-shrink:0\"></div>\n      <span id=\"sync-label\" style=\"font-size:12px;color:var(--text-m)\">${hasToken ? 'Connecté' : 'Non configuré'}</span>\n      ${gistId ? `<a href=\"https://gist.github.com/${gistId}\" target=\"_blank\" rel=\"noopener\" style=\"font-size:10px;color:var(--accent);margin-left:auto\">Voir le Gist ↗</a>` : ''}\n    </div>\n    ${!hasToken ? `\n      <input class=\"settings-input\" type=\"password\" id=\"gist-token-input\"\n        placeholder=\"ghp_votre_token_github…\"\n        style=\"margin-bottom:8px\"\n        onkeydown=\"if(event.key==='Enter')saveGistSettings()\"/>\n      <p style=\"font-size:10px;color:var(--text-f);margin-bottom:8px;line-height:1.5\">\n        Créer sur <a href=\"https://github.com/settings/tokens\" target=\"_blank\" style=\"color:var(--accent)\">github.com/settings/tokens</a><br>\n        Cocher uniquement la permission <strong style=\"color:var(--text-m)\">gist</strong>\n      </p>\n      <button id=\"gist-save-btn\" class=\"btn-primary\" onclick=\"saveGistSettings()\" style=\"width:100%\">Connecter</button>\n    ` : `\n      <div style=\"display:flex;gap:6px;flex-wrap:wrap\">\n        <button class=\"btn-sm\" onclick=\"manualSyncSave()\" style=\"flex:1\">⬆ Sauvegarder</button>\n        <button class=\"btn-sm\" onclick=\"manualSyncLoad()\" style=\"flex:1\">⬇ Charger</button>\n        <button class=\"btn-sm\" onclick=\"disconnectGist()\" style=\"flex:1;color:var(--danger)\">Déconnecter</button>\n      </div>\n    `}\n  `;\n\n  // Restore status dot if connected\n  if (hasToken) updateSyncStatus('ok');\n}\n\n// ── initSync — called from initApp (just renders UI) ──\n// Actual data loading happens in startApp() BEFORE initApp()\nfunction initSync() {\n  renderSyncSection();\n  // Schedule a background sync save to push any local changes\n  if (getSyncToken() && getSyncGistId()) {\n    scheduleSyncSave();\n  }\n}\n\n/* ══════════════════════════════════════\n   APP.JS — Bootstrap & Login\n══════════════════════════════════════ */\n\nwindow.dashReset = function() {\n  if (confirm('Réinitialiser le dashboard ? Toutes les données seront perdues.')) {\n    localStorage.clear(); sessionStorage.clear(); location.reload();\n  }\n};\n\n// ── Auto-login if same session ────────────────\n(function checkSession() {\n  if (sessionStorage.getItem('dash_logged_in') === '1') {\n    if (document.readyState === 'loading') {\n      document.addEventListener('DOMContentLoaded', () => startApp());\n    } else {\n      startApp();\n    }\n  }\n})();\n\n// ── Wire login buttons ─────────────────────────\ndocument.addEventListener('DOMContentLoaded', function() {\n  const btn  = document.getElementById('login-btn');\n  const uInp = document.getElementById('login-user');\n  const pInp = document.getElementById('login-pass');\n  if (btn)  btn.addEventListener('click', tryLogin);\n  if (uInp) uInp.addEventListener('keydown', e => { if(e.key==='Enter') pInp?.focus(); });\n  if (pInp) pInp.addEventListener('keydown', e => { if(e.key==='Enter') tryLogin(); });\n});\n\nlet _loginAttempts = 0;\n\nfunction tryLogin() {\n  const uInp = document.getElementById('login-user');\n  const pInp = document.getElementById('login-pass');\n  const err  = document.getElementById('login-err');\n  const user = (uInp?.value || '').trim();\n  const pass = pInp?.value || '';\n\n  if (user === S.username && pass === S.password) {\n    _loginAttempts = 0;\n    sessionStorage.setItem('dash_logged_in', '1');\n    document.getElementById('login-overlay').classList.add('hidden');\n    document.getElementById('app').classList.add('visible');\n    startApp();\n  } else {\n    _loginAttempts++;\n    err.textContent = _loginAttempts >= 5\n      ? 'Trop de tentatives — utilisez Réinitialiser ci-dessous'\n      : (!user || user !== S.username) ? 'Identifiant incorrect' : 'Mot de passe incorrect';\n    err.style.display = 'block';\n    if (pInp) pInp.value = '';\n    if (_loginAttempts < 5) setTimeout(() => { err.style.display = 'none'; }, 3000);\n  }\n}\n\n// ── startApp : load Gist FIRST, then render ───\nasync function startApp() {\n  // Show loading overlay while syncing\n  const token  = typeof getSyncToken  === 'function' ? getSyncToken()  : '';\n  const gistId = typeof getSyncGistId === 'function' ? getSyncGistId() : '';\n\n  if (token && gistId) {\n    showLoadingOverlay('Synchronisation en cours…');\n    try {\n      await syncLoad();            // ← load remote state BEFORE rendering\n    } catch(e) {\n      console.warn('Sync load failed, using local state:', e);\n    }\n    hideLoadingOverlay();\n  }\n\n  initApp();                       // ← render with (possibly updated) S\n}\n\n// ── Loading overlay ────────────────────────────\nfunction showLoadingOverlay(msg) {\n  let el = document.getElementById('sync-loading-overlay');\n  if (!el) {\n    el = document.createElement('div');\n    el.id = 'sync-loading-overlay';\n    el.style.cssText = `\n      position:fixed;inset:0;z-index:8000;\n      background:var(--bg);\n      display:flex;flex-direction:column;align-items:center;justify-content:center;\n      gap:16px;\n      transition:opacity 0.3s ease;\n    `;\n    el.innerHTML = `\n      <div style=\"\n        width:40px;height:40px;border-radius:50%;\n        border:3px solid var(--surface3);\n        border-top-color:var(--accent);\n        animation:spin 0.8s linear infinite;\n      \"></div>\n      <style>@keyframes spin{to{transform:rotate(360deg)}}</style>\n      <span id=\"sync-loading-msg\" style=\"font-size:13px;color:var(--text-m)\">${msg}</span>\n    `;\n    document.body.appendChild(el);\n  } else {\n    document.getElementById('sync-loading-msg').textContent = msg;\n    el.style.opacity = '1';\n    el.style.display = 'flex';\n  }\n}\n\nfunction hideLoadingOverlay() {\n  const el = document.getElementById('sync-loading-overlay');\n  if (!el) return;\n  el.style.opacity = '0';\n  setTimeout(() => { el.style.display = 'none'; }, 300);\n}\n\n// ── Init App (render UI from current S) ───────\nfunction initApp() {\n  applyTheme();\n  applyI18n();\n  buildColorOptions();\n  buildLangOptions();\n  syncBgControls();\n\n  const un = document.getElementById('user-name');\n  if (un) un.textContent = S.displayName || 'Ayidna';\n  const dni = document.getElementById('display-name-input');\n  if (dni) dni.value = S.displayName || 'Ayidna';\n  const uinp = document.getElementById('settings-username');\n  if (uinp) uinp.value = S.username || 'admin';\n  const dt = document.getElementById('dark-toggle');\n  if (dt) dt.classList.toggle('on', S.dark);\n\n  initCalendar();\n  initTranslate();\n  initSearch();\n  initNotifications();\n  initWeatherClock();\n\n  renderTodoTabs();\n  renderTodos();\n  renderAllSections();\n  initMobileSidebar();\n\n  // Render sync section in settings (UI only, no network call)\n  if (typeof renderSyncSection === 'function') renderSyncSection();\n}\n\n// ── Full re-render (called after manual sync load) ──\nfunction reRenderAll() {\n  applyTheme(); applyI18n(); buildColorOptions(); buildLangOptions(); syncBgControls();\n  const un = document.getElementById('user-name');\n  if (un) un.textContent = S.displayName || 'Ayidna';\n  const dni = document.getElementById('display-name-input');\n  if (dni) dni.value = S.displayName || 'Ayidna';\n  const dt = document.getElementById('dark-toggle');\n  if (dt) dt.classList.toggle('on', S.dark);\n  renderTodoTabs(); renderTodos();\n  renderAllSections(); renderCalendar();\n  if (typeof renderSyncSection === 'function') renderSyncSection();\n}\n\n// ── Mobile Sidebar ─────────────────────────────\nfunction initMobileSidebar() {\n  const btn = document.getElementById('mobile-menu-btn');\n  if (!btn) return;\n  if (!document.getElementById('sidebar-nav')) {\n    const nav = document.createElement('div');\n    nav.id = 'sidebar-nav';\n    nav.innerHTML = `\n      <div class=\"sidebar-inner\">\n        <a class=\"logo\" href=\"index.html\" style=\"margin-bottom:16px;display:block\">Dashboard</a>\n        <div class=\"sidebar-title\">Pages</div>\n        <a class=\"sidebar-link\" href=\"watchlist.html\">🎬 Watchlist</a>\n        <a class=\"sidebar-link\" href=\"music.html\">🎵 Musique</a>\n        <div class=\"sidebar-title\">Navigation</div>\n        <button class=\"sidebar-link\" onclick=\"scrollToCard('todo-card');closeSidebar()\">✅ Tâches</button>\n        <button class=\"sidebar-link\" onclick=\"scrollToCard('translate-card');closeSidebar()\">🌍 Traduction</button>\n        <button class=\"sidebar-link\" onclick=\"scrollToCard('calendar-card');closeSidebar()\">📅 Calendrier</button>\n        <div class=\"sidebar-title\">Outils</div>\n        <button class=\"sidebar-link\" onclick=\"toggleSettings();closeSidebar()\">⚙️ Paramètres</button>\n        <button class=\"sidebar-link\" onclick=\"toggleEditMode();closeSidebar()\">✏️ Mode Édition</button>\n      </div>`;\n    nav.addEventListener('click', e => { if(e.target === nav) closeSidebar(); });\n    document.body.appendChild(nav);\n  }\n  btn.addEventListener('click', () => {\n    document.getElementById('sidebar-nav').classList.toggle('open');\n  });\n}\n\nfunction closeSidebar() { document.getElementById('sidebar-nav')?.classList.remove('open'); }\nfunction scrollToCard(id) { document.getElementById(id)?.scrollIntoView({ behavior:'smooth', block:'start' }); }\n\n","captured_at":"2026-08-12T08:16:57.196839+00:00","fetch_method":"inline"}],"intercepted_scripts":[],"secondary_scripts":[],"meta_tags":[{"charset":"UTF-8"},{"name":"viewport","content":"width=device-width, initial-scale=1.0"}],"console_logs":[{"level":"DEBUG","source":"recommendation","message":"https://ayidna-dashboard.pages.dev/ - [DOM] Password field is not contained in a form: (More info: https://goo.gl/9p2vKq) %o","timestamp":1786522553683},{"level":"DEBUG","source":"recommendation","message":"https://ayidna-dashboard.pages.dev/ - [DOM] Password field is not contained in a form: (More info: https://goo.gl/9p2vKq) %o","timestamp":1786522553683}],"error":null,"http_transactions":[{"request":{"url":"https://ayidna-dashboard.pages.dev/","domain":"ayidna-dashboard.pages.dev","method":"GET","headers":{"Pragma":"no-cache","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\"","Upgrade-Insecure-Requests":"1"},"wallTime":1786522553.143336,"timestamp":"2026-08-12T08:16:57.274950+00:00","devtools_timestamp":8890891.740977},"response":{"url":"https://ayidna-dashboard.pages.dev/","status":200,"timing":{"dnsEnd":-1,"sslEnd":8.251,"pushEnd":0,"sendEnd":8.643,"dnsStart":-1,"proxyEnd":-1,"sslStart":0,"pushStart":0,"sendStart":8.402,"connectEnd":8.258,"proxyStart":-1,"requestTime":8890891.741497,"workerReady":-1,"workerStart":-1,"connectStart":0,"workerFetchStart":-1,"receiveHeadersEnd":418.254,"receiveHeadersStart":418.094,"workerRespondWithSettled":-1},"headers":{"nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Wed, 12 Aug 2026 08:15:53 GMT","cf-ray":"a29e08e59817d2c7-FRA","server":"cloudflare","alt-svc":"h3=\":443\"; ma=86400","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=%2ByG0%2BpjwbsV1Z9KzzygfvDdlleoHxlO2g2pjfFixNtCm5UYxHtjgX%2Fj54D%2BorVW2c7hPLGVJhkwIZtxWq%2B6%2FziaGGrzLSt55gdTqZ%2F3HN%2FsDgwaTeAutOTZIokfXmzOBLA1hAcWTaQH7A5U8cA%3D%3D\"}]}","content-type":"text/html; charset=utf-8","cache-control":"public, max-age=0, must-revalidate","referrer-policy":"strict-origin-when-cross-origin","content-encoding":"br","x-content-type-options":"nosniff","access-control-allow-origin":"*"},"mimeType":"text/html","protocol":"h2","statusText":"","responseTime":8890892.160669,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":41058},"duration_ms":424},{"request":{"url":"https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;1,9..40,300&display=swap","domain":"fonts.googleapis.com","method":"GET","headers":{"Pragma":"no-cache","Referer":"https://ayidna-dashboard.pages.dev/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.565904,"timestamp":"2026-08-12T08:16:57.276096+00:00","devtools_timestamp":8890892.163516},"response":{"url":"https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;1,9..40,300&display=swap","status":200,"timing":{"dnsEnd":-1,"sslEnd":25.557,"pushEnd":0,"sendEnd":26.015,"dnsStart":-1,"proxyEnd":-1,"sslStart":19.562,"pushStart":0,"sendStart":25.784,"connectEnd":25.568,"proxyStart":-1,"requestTime":8890892.164291,"workerReady":-1,"workerStart":-1,"connectStart":0.579,"workerFetchStart":-1,"receiveHeadersEnd":92.687,"receiveHeadersStart":92.48,"workerRespondWithSettled":-1},"headers":{"date":"Wed, 12 Aug 2026 08:15:53 GMT","link":"<https://fonts.gstatic.com>; rel=preconnect; crossorigin","vary":"Sec-Fetch-Dest, Sec-Fetch-Mode, Sec-Fetch-Site","server":"ESF","alt-svc":"h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000","expires":"Wed, 12 Aug 2026 08:15:53 GMT","content-type":"text/css; charset=utf-8","cache-control":"private, max-age=86400, stale-while-revalidate=604800","last-modified":"Wed, 12 Aug 2026 08:15:53 GMT","x-frame-options":"SAMEORIGIN","content-encoding":"gzip","x-xss-protection":"0","timing-allow-origin":"*","x-content-type-options":"nosniff","strict-transport-security":"max-age=31536000","cross-origin-opener-policy":"same-origin-allow-popups","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin"},"mimeType":"text/css","protocol":"h2","statusText":"","responseTime":8890892.258017,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":1091},"duration_ms":94},{"request":{"url":"https://fonts.gstatic.com/s/dmsans/v17/rP2Hp2ywxg089UriCZOIHQ.woff2","domain":"fonts.gstatic.com","method":"GET","headers":{"Origin":"https://ayidna-dashboard.pages.dev","Pragma":"no-cache","Referer":"https://fonts.googleapis.com/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.663511,"timestamp":"2026-08-12T08:16:57.277112+00:00","devtools_timestamp":8890892.261127},"response":{"url":"https://fonts.gstatic.com/s/dmsans/v17/rP2Hp2ywxg089UriCZOIHQ.woff2","status":200,"timing":{"dnsEnd":-1,"sslEnd":15.889,"pushEnd":0,"sendEnd":17.044,"dnsStart":-1,"proxyEnd":-1,"sslStart":8.453,"pushStart":0,"sendStart":16.122,"connectEnd":15.904,"proxyStart":-1,"requestTime":8890892.26149,"workerReady":-1,"workerStart":-1,"connectStart":0.378,"workerFetchStart":-1,"receiveHeadersEnd":93.551,"receiveHeadersStart":93.379,"workerRespondWithSettled":-1},"headers":{"age":"325440","date":"Sat, 08 Aug 2026 13:51:53 GMT","server":"sffe","alt-svc":"h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000","expires":"Sun, 08 Aug 2027 13:51:53 GMT","report-to":"{\"group\":\"apps-themes\",\"max_age\":2592000,\"endpoints\":[{\"url\":\"https://csp.withgoogle.com/csp/report-to/apps-themes\"}]}","content-type":"font/woff2","accept-ranges":"bytes","cache-control":"public, max-age=31536000","last-modified":"Wed, 10 Sep 2025 16:30:14 GMT","content-length":"62724","x-xss-protection":"0","timing-allow-origin":"*","x-content-type-options":"nosniff","cross-origin-opener-policy":"same-origin; report-to=\"apps-themes\"","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin","content-security-policy-report-only":"require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/apps-themes"},"mimeType":"font/woff2","protocol":"h2","statusText":"","responseTime":8890892.358863,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":63293},"duration_ms":96},{"request":{"url":"https://fonts.gstatic.com/s/syne/v24/8vIH7w4qzmVxm2BL9A.woff2","domain":"fonts.gstatic.com","method":"GET","headers":{"Origin":"https://ayidna-dashboard.pages.dev","Pragma":"no-cache","Referer":"https://fonts.googleapis.com/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.665964,"timestamp":"2026-08-12T08:16:57.277604+00:00","devtools_timestamp":8890892.26358},"response":{"url":"https://fonts.gstatic.com/s/syne/v24/8vIH7w4qzmVxm2BL9A.woff2","status":200,"timing":{"dnsEnd":-1,"sslEnd":-1,"pushEnd":0,"sendEnd":14.801,"dnsStart":-1,"proxyEnd":-1,"sslStart":-1,"pushStart":0,"sendStart":14.443,"connectEnd":-1,"proxyStart":-1,"requestTime":8890892.26393,"workerReady":-1,"workerStart":-1,"connectStart":-1,"workerFetchStart":-1,"receiveHeadersEnd":143.688,"receiveHeadersStart":143.569,"workerRespondWithSettled":-1},"headers":{"age":"225758","date":"Sun, 09 Aug 2026 17:33:15 GMT","server":"sffe","alt-svc":"h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000","expires":"Mon, 09 Aug 2027 17:33:15 GMT","report-to":"{\"group\":\"apps-themes\",\"max_age\":2592000,\"endpoints\":[{\"url\":\"https://csp.withgoogle.com/csp/report-to/apps-themes\"}]}","content-type":"font/woff2","accept-ranges":"bytes","cache-control":"public, max-age=31536000","last-modified":"Tue, 16 Sep 2025 13:27:50 GMT","content-length":"34608","x-xss-protection":"0","timing-allow-origin":"*","x-content-type-options":"nosniff","cross-origin-opener-policy":"same-origin; report-to=\"apps-themes\"","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin","content-security-policy-report-only":"require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/apps-themes"},"mimeType":"font/woff2","protocol":"h2","statusText":"","responseTime":8890892.409852,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":34752},"duration_ms":145},{"request":{"url":"https://fonts.gstatic.com/s/syne/v24/8vIH7w4qzmVxm2BL9A.woff2","domain":"fonts.gstatic.com","method":"GET","headers":{"Origin":"https://ayidna-dashboard.pages.dev","Pragma":"no-cache","Referer":"https://fonts.googleapis.com/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.666065,"timestamp":"2026-08-12T08:16:57.278071+00:00","devtools_timestamp":8890892.263706},"response":{"url":"https://fonts.gstatic.com/s/syne/v24/8vIH7w4qzmVxm2BL9A.woff2","status":200,"timing":{"dnsEnd":-1,"sslEnd":-1,"pushEnd":0,"sendEnd":14.537,"dnsStart":-1,"proxyEnd":-1,"sslStart":-1,"pushStart":0,"sendStart":14.28,"connectEnd":-1,"proxyStart":-1,"requestTime":8890892.264199,"workerReady":-1,"workerStart":-1,"connectStart":-1,"workerFetchStart":-1,"receiveHeadersEnd":144.867,"receiveHeadersStart":144.809,"workerRespondWithSettled":-1},"headers":{"age":"225758","date":"Sun, 09 Aug 2026 17:33:15 GMT","server":"sffe","alt-svc":"h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000","expires":"Mon, 09 Aug 2027 17:33:15 GMT","report-to":"{\"group\":\"apps-themes\",\"max_age\":2592000,\"endpoints\":[{\"url\":\"https://csp.withgoogle.com/csp/report-to/apps-themes\"}]}","content-type":"font/woff2","accept-ranges":"bytes","cache-control":"public, max-age=31536000","last-modified":"Tue, 16 Sep 2025 13:27:50 GMT","content-length":"34608","x-xss-protection":"0","timing-allow-origin":"*","x-content-type-options":"nosniff","cross-origin-opener-policy":"same-origin; report-to=\"apps-themes\"","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin","content-security-policy-report-only":"require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/apps-themes"},"mimeType":"font/woff2","protocol":"h2","statusText":"","responseTime":8890892.410665,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":34672},"duration_ms":146},{"request":{"url":"https://fonts.gstatic.com/s/dmsans/v17/rP2Hp2ywxg089UriCZOIHQ.woff2","domain":"fonts.gstatic.com","method":"GET","headers":{"Origin":"https://ayidna-dashboard.pages.dev","Pragma":"no-cache","Referer":"https://fonts.googleapis.com/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.666127,"timestamp":"2026-08-12T08:16:57.278516+00:00","devtools_timestamp":8890892.263768},"response":{"url":"https://fonts.gstatic.com/s/dmsans/v17/rP2Hp2ywxg089UriCZOIHQ.woff2","status":200,"timing":{"dnsEnd":-1,"sslEnd":-1,"pushEnd":0,"sendEnd":14.314,"dnsStart":-1,"proxyEnd":-1,"sslStart":-1,"pushStart":0,"sendStart":13.757,"connectEnd":-1,"proxyStart":-1,"requestTime":8890892.264412,"workerReady":-1,"workerStart":-1,"connectStart":-1,"workerFetchStart":-1,"receiveHeadersEnd":110.524,"receiveHeadersStart":110.355,"workerRespondWithSettled":-1},"headers":{"age":"325440","date":"Sat, 08 Aug 2026 13:51:53 GMT","server":"sffe","alt-svc":"h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000","expires":"Sun, 08 Aug 2027 13:51:53 GMT","report-to":"{\"group\":\"apps-themes\",\"max_age\":2592000,\"endpoints\":[{\"url\":\"https://csp.withgoogle.com/csp/report-to/apps-themes\"}]}","content-type":"font/woff2","accept-ranges":"bytes","cache-control":"public, max-age=31536000","last-modified":"Wed, 10 Sep 2025 16:30:14 GMT","content-length":"62724","x-xss-protection":"0","timing-allow-origin":"*","x-content-type-options":"nosniff","cross-origin-opener-policy":"same-origin; report-to=\"apps-themes\"","access-control-allow-origin":"*","cross-origin-resource-policy":"cross-origin","content-security-policy-report-only":"require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/apps-themes"},"mimeType":"font/woff2","protocol":"h2","statusText":"","responseTime":8890892.378955,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":62797},"duration_ms":113},{"request":{"url":"https://ayidna-dashboard.pages.dev/favicon.ico","domain":"ayidna-dashboard.pages.dev","method":"GET","headers":{"Pragma":"no-cache","Referer":"https://ayidna-dashboard.pages.dev/","sec-ch-ua":"\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","Cache-Control":"no-cache, no-store, must-revalidate","sec-ch-ua-mobile":"?0","sec-ch-ua-platform":"\"Windows\""},"wallTime":1786522553.815227,"timestamp":"2026-08-12T08:16:57.279478+00:00","devtools_timestamp":8890892.41286},"response":{"url":"https://ayidna-dashboard.pages.dev/favicon.ico","status":200,"timing":{"dnsEnd":-1,"sslEnd":-1,"pushEnd":0,"sendEnd":0.455,"dnsStart":-1,"proxyEnd":-1,"sslStart":-1,"pushStart":0,"sendStart":0.325,"connectEnd":-1,"proxyStart":-1,"requestTime":8890892.413041,"workerReady":-1,"workerStart":-1,"connectStart":-1,"workerFetchStart":-1,"receiveHeadersEnd":73.778,"receiveHeadersStart":73.618,"workerRespondWithSettled":-1},"headers":{"nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Wed, 12 Aug 2026 08:15:53 GMT","cf-ray":"a29e08e96c8ad2c7-FRA","server":"cloudflare","alt-svc":"h3=\":443\"; ma=86400","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=kdW7xaJje0DgCsNlsixY29pOoSXJePqJlVWXqPVS2OXdcyyrfEUmN8I%2BC1foBlyvHDwD2E1ot1z9m9Ddpxi5iQSodu%2BJfB%2F5%2FVwexMkba2OczinBG5Vfo1I%2FxdxrwnCy%2FruDQCo6pR5PI28TNA%3D%3D\"}]}","content-type":"text/html; charset=utf-8","cache-control":"public, max-age=0, must-revalidate","referrer-policy":"strict-origin-when-cross-origin","content-encoding":"br","x-content-type-options":"nosniff","access-control-allow-origin":"*"},"mimeType":"text/html","protocol":"h2","statusText":"","responseTime":8890892.487502,"securityState":"insecure","remoteIPAddress":null,"encodedDataLength":40820},"duration_ms":78}],"redirect_chains":[],"redirects":[],"security_verdict":{"verdict":"Low Risk","confidence":77,"risk_level":"low","risk_factors":[],"overall_score":23,"recommendations":[],"detailed_analysis":{"html_forms":{"score":50,"issues":[],"password_fields":0,"impersonated_brand":null,"brand_mismatch_detected":false,"impersonated_brand_slug":null,"disguised_password_fields":0,"brand_impersonation_detected":false},"url_analysis":{"score":65,"issues":[],"positive_signals":["HTTPS encryption used"],"suspicious_patterns":[]},"safe_browsing":{"score":100,"issues":[],"threats":[],"positive_signals":["No Google Safe Browsing threats detected"]},"clone_detection":{"score":100,"issues":[],"warnings":[],"positive_signals":["No visual similarity to known brand sites"]},"rpki_validation":{"total":4,"total_risk":0,"valid_count":4,"invalid_count":0,"not_found_count":0},"network_security":{"score":65,"issues":[],"mixed_content":false,"secure_requests":7,"security_headers":{"detected":true},"insecure_requests":0,"certificate_issues":[]},"phishing_signals":{"score":100,"issues":[],"details":{"matched_brand":null,"signals_detected":[],"is_legitimate_domain":false},"warnings":[]},"technology_risks":{"score":50,"issues":[],"security_technologies":[],"vulnerable_technologies":[]},"redirect_analysis":{"score":50,"issues":[],"total_redirects":0,"blob_url_detected":false,"protocol_downgrades":0,"suspicious_patterns":0,"cross_domain_redirects":0,"compromised_wordpress_detected":false}},"threat_categories":[],"security_indicators":{"negative":[],"positive":["Server IPs have valid RPKI ROA coverage","HTTPS encryption used","Good network security practices","No Google Safe Browsing threats detected","No visual similarity to known brand sites"],"warnings":[]}},"tracker_analysis":{"summary":{"total_trackers":0,"unique_companies":0,"highest_risk_category":null},"privacy_concerns":[],"detected_trackers":[],"tracker_categories":{"other":[],"video":[],"privacy":[],"security":[],"analytics":[],"marketing":[],"advertising":[],"performance":[],"social_media":[],"apm_monitoring":[],"authentication":[],"error_tracking":[],"fingerprinting":[],"consent_management":[],"first_party_analytics":[]},"unique_ids_extracted":{}},"technologies":{"detected":[{"name":"HTTP/3","version":null,"category":"wappalyzer","confidence":40,"detected_at":"2026-08-12T08:17:08.877549Z","website":null,"description":null,"details":{"cpe":null,"source":"wappalyzer","implies":[],"detected_by":["headers"],"detection_details":[{"method":"headers","matches":[{"value":"h3=\":443\"; ma=86400","header":"alt-svc","pattern":"h3"}]}],"confidence_breakdown":{"headers":40}}},{"name":"Cloudflare Bot Management","version":null,"category":"wappalyzer","confidence":40,"detected_at":"2026-08-12T08:17:08.877549Z","website":null,"description":null,"details":{"cpe":null,"source":"wappalyzer","implies":["Cloudflare"],"detected_by":["headers"],"detection_details":[{"method":"headers","matches":[{"type":"presence","value":"a29e08e59817d2c7-FRA","header":"cf-ray"}]}],"confidence_breakdown":{"headers":40}}},{"name":"Cloudflare","version":null,"category":"wappalyzer","confidence":40,"detected_at":"2026-08-12T08:17:08.877549Z","website":null,"description":null,"details":{"cpe":null,"source":"wappalyzer","implies":[],"detected_by":["headers"],"detection_details":[{"method":"headers","matches":[{"type":"presence","value":"a29e08e59817d2c7-FRA","header":"cf-ray"},{"value":"cloudflare","header":"server","pattern":"^cloudflare$"}]}],"confidence_breakdown":{"headers":40}}}]},"domains":["ayidna-dashboard.pages.dev","fonts.googleapis.com","fonts.gstatic.com"],"ip_addresses":["142.251.14.95","188.114.96.3"],"page_stats":{"total_size_kb":271.9560546875,"total_requests":7,"unique_domains":3,"total_size_bytes":278483},"screenshot_hashes":{"crop_resistant":"0008303032300800","ahash":"0000000000000000000110000001100000011000000110000000000000000000","ahash_hex":"0000181818180000","ahash_int":"26491762507776","phash":"1100110001100110001100111001100111001100011001100011001110011001","phash_hex":"cc663399cc663399","phash_int":"14728516367014048665","dhash":"0000000000001000001100000011000000110010001100000000100000000000","dhash_hex":"0008303032300800","dhash_int":"2304783372257280","whash":"0000000000000000001111000011110000111100001111000011000000110000","whash_hex":"00003c3c3c3c3030","whash_int":"66229406281776"},"favicon_hash":{"url":"https://ayidna-dashboard.pages.dev/favicon.ico","data_b64":null,"md5_hash":"a02c94b3fe8fa68657066707d4dabc96","mmh3_hash":868147261,"stored_size":167463,"original_size":167463},"fuzzy_hashes":{"tlsh":"T1AAF3B572327515317567E96D73BB8F1A3224A003F906D5647AAC20C44FFAEA4CD73AE8","sdhash":"sdhash:3:167573:DUCEeQJAIiI4VgoE0HQtJo5oIIIC0RwnClQIYgkRCoGhQBcAcgQJiANtaqBNIlcYgkjIyhlLwBuQCOGdgIBEMI31CqBpSswe","ssdeep":"3072:VcsEyzZjLYHqtOPpVL4d2IKxVtJkuRwJVQap3yCW:VcsEyzZjLYHqkHL4d2IKxVtJkuRwJVQT"},"content_analysis":{"modules":{"language":{"results":{"confidence":0.8,"text_length":1044,"language_info":{"name":"French","script":"Latin","direction":"ltr"},"agreement_ratio":1.0,"detection_method":"html_attribute_validated","primary_language":"fr","script_detection":{"script":null,"confidence":0.0},"consistency_score":1.0,"dominant_language":"fr","character_analysis":{"likely_language":"fr","character_counts":{"french_specific":23,"german_specific":0,"polish_specific":0,"norwegian_danish":0,"swedish_specific":0}},"detected_languages":{},"html_lang_warnings":[],"html_lang_attribute":"fr","html_lang_trust_score":1.0,"language_distribution":{"headings":{"language":"fr","confidence":0.5159560585634441},"body_text":{"language":"fr","confidence":0.49999827512374245}}},"version":"1.0.0","timestamp":1786522626.6497798},"classification":{"results":{"website_type":"webapp","all_categories":[{"name":"cryptocurrency blockchain","confidence":0.553987979888916},{"name":"real estate property","confidence":0.541408896446228},{"name":"healthcare medical","confidence":0.500732421875},{"name":"news media journalism","confidence":0.4520520567893982},{"name":"government public service","confidence":0.4122934639453888}],"ocr_tiebreaker":{"used":true,"ocr_result":{"category":"cryptocurrency blockchain","confidence":0.553987979888916},"html_original":{"category":"technology software","confidence":0.3562226891517639}},"primary_category":"cryptocurrency blockchain","language_agnostic":true,"primary_confidence":0.553987979888916,"structural_features":{"og_type":null,"has_login":true,"has_crypto":false,"has_search":false,"domain_type":"unknown","has_payment":false,"has_articles":false,"has_comments":false,"has_products":false,"schema_types":[],"has_financial":false,"has_newsletter":false,"phishing_indicators":1},"classification_method":"ml+structural+ocr_tiebreaker"},"version":"1.0.0","timestamp":1786522631.4106543}},"scan_id":"22375397-1a27-454d-9187-41578701c6d8","analyzed_at":"2026-08-12T08:17:06.598609Z"},"domain_rankings":{"has_top_1k":false,"has_top_100":false,"has_top_10k":false,"has_top_100k":false,"top_1k_count":0,"top_100_count":0,"top_10k_count":0,"total_domains":1,"primary_domain":"ayidna-dashboard.pages.dev","ranked_domains":[],"top_100k_count":0,"primary_ranking":null,"unranked_domains":[{"domain":"ayidna-dashboard.pages.dev","is_primary":true}],"suspicious_unranked":false},"rdap_data":{"domains":[{"domain":"pages.dev","handle":"4394CC0DF-DEV","parent_handle":"","name":"pages.dev","whois_server":"","type":"domain","terms_of_service_url":"","description":[],"last_changed_date":"2026-06-09T12:00:52.612000Z","registration_date":"2020-09-02T02:33:29.228000Z","expiration_date":"2027-09-02T02:33:29.228000Z","rdap_url":"https://pubapi.registry.google/rdap/domain/pages.dev","registrar":null,"status":["client delete prohibited","client transfer prohibited","client update prohibited"],"nameservers":["adi.ns.cloudflare.com","karl.ns.cloudflare.com"],"entities":{"abuse":[{"name":"Abuse Team","type":"entity","email":"registrar-abuse@cloudflare.com"}],"registrar":[{"url":"https://pubapi.registry.google/rdap/entity/1910","name":"CloudFlare, Inc.","type":"entity","handle":"1910"}]},"lookup_timestamp":"2026-08-12T08:17:06.944334Z"}],"ips":[{"ip_address":"188.114.97.3/32","handle":"188.114.96.0 - 188.114.99.255","parent_handle":"188.114.96.0 - 188.114.111.255","name":"CLOUDFLARENET-EU","whois_server":"whois.ripe.net","type":"ip network","terms_of_service_url":"http://www.ripe.net/db/support/db-terms-conditions.pdf","description":["CloudFlare, Inc.","101 Townsend Street, San Francisco, CA 94107, US","+1 (650) 319-8930","https://cloudflare.com/","https://cloudflare.com/abuse"],"last_changed_date":"2015-10-16T16:26:10Z","registration_date":"2015-10-16T16:26:10Z","expiration_date":null,"rdap_url":"https://rdap.db.ripe.net/ip/188.114.97.3","rir":"ripe","country":"US","ip_version":4,"assignment_type":"assigned pa","network":"188.114.96.0/22","entities":{"abuse":[{"name":"Cloudflare Abuse Contact","type":"entity","email":"abuse@cloudflare.com","handle":"CF6885-RIPE","address":{"po_box":"","region":"","country":"","locality":"","ext_address":"","postal_code":"","street_address":""}}],"technical":[{"rir":"ripe","tel":"+49 89 2555 2276","url":"https://rdap.db.ripe.net/entity/CTC6-RIPE","name":"Cloudflare Technical Contact","type":"entity","handle":"CTC6-RIPE","address":{"po_box":"","region":"","country":"","locality":"","ext_address":"","postal_code":"","street_address":""}}],"registrant":[{"rir":"ripe","url":"https://rdap.db.ripe.net/entity/MNT-CLOUDFLARE","name":"MNT-CLOUDFLARE","type":"entity","handle":"MNT-CLOUDFLARE"}],"administrative":[{"rir":"ripe","tel":"+49 89 2555 2276","url":"https://rdap.db.ripe.net/entity/CAC80-RIPE","name":"Cloudflare Abuse Contact","type":"entity","handle":"CAC80-RIPE","address":{"po_box":"","region":"","country":"","locality":"","ext_address":"","postal_code":"","street_address":""}}]},"lookup_timestamp":"2026-08-12T08:17:07.365162Z"}]},"domains_contacted":["ayidna-dashboard.pages.dev","fonts.googleapis.com","fonts.gstatic.com"],"unique_asns":[15169,13335],"countries":["US"],"ip_table":[{"ip":"142.251.14.95","asn":"AS15169","asn_name":"Google LLC","country":"US","country_name":"United States","city":null,"state":null,"cdn":{"category":"cdn","provider":"google"},"requests":4},{"ip":"188.114.96.3","asn":"AS13335","asn_name":"Cloudflare, Inc.","country":"US","country_name":"United States","city":null,"state":null,"cdn":{"category":"waf","provider":"cloudflare"},"requests":3}],"asn_table":[{"asn":"15169 (Google LLC)","org":"Google LLC"},{"asn":"13335 (Cloudflare, Inc.)","org":"Cloudflare, Inc."}],"asns":[15169,13335],"primary_asn":15169,"primary_ip":"142.251.14.95","asn_orgs":{"13335":"Cloudflare, Inc.","15169":"Google LLC"},"asn_names":["Google LLC","Cloudflare, Inc."],"ip_asn_info":{"ip_table":[{"ip":"142.251.14.95","asn":"AS15169","asn_name":"Google LLC","country":"US","country_name":"United States","city":null,"state":null,"cdn":{"category":"cdn","provider":"google"},"requests":4},{"ip":"188.114.96.3","asn":"AS13335","asn_name":"Cloudflare, Inc.","country":"US","country_name":"United States","city":null,"state":null,"cdn":{"category":"waf","provider":"cloudflare"},"requests":3}],"total_ips":2,"countries":["US"]},"security_headers":{"headers":{},"missing_headers":[],"analyzed":false},"csp_analysis":null,"csp_policy":{"policy":"require-trusted-types-for 'script'; report-uri https://csp.withgoogle.com/csp/apps-themes","directives":{"require-trusted-types-for":["'script'"],"report-uri":["https://csp.withgoogle.com/csp/apps-themes"]},"security_analysis":{"allows_unsafe_inline_scripts":false,"allows_unsafe_inline_styles":false,"allows_unsafe_eval":false,"allows_data_uri":false,"has_default_src":false,"has_script_src":false,"has_style_src":false,"has_frame_ancestors":false,"strictness_score":0,"issues":[],"recommendations":["Add frame-ancestors directive to prevent clickjacking","Add default-src or script-src directive"]},"extracted_at":"2026-08-12T08:16:57.351957Z","source":"report-only-header","report_only":true},"iframes":{"iframes":[],"iframe_summary":{}},"cors_findings":null,"network_requests":[],"total_requests":0,"ai_security_analysis":{"verdict":"The site shows no malicious indicators and only a simple dashboard; low risk.","classification":"LOW_RISK","risk_score":2,"confidence_percentage":78,"threat_type":"Not Applicable","key_evidence":["No credential or payment forms detected","No Indicators of Compromise matches","No JavaScript malware hunting-rule patterns","No network IDS alerts","Subdomain on hosting platform with unknown creation date but no malicious activity"],"risk_factors":[],"safety_factors":["Absence of forms and credential collection","No malicious network activity or external threats","Content appears to be a personal dashboard with no brand impersonation"],"recommended_action":"Use with caution","skipped_reason":null,"assessed_by":"ai","confidence_fixed":false},"network_data":{"redirects":[],"console_logs":[],"ip_addresses":["142.251.14.95","188.114.96.3"],"total_requests":4,"dns_resolutions":{"fonts.googleapis.com":{"ip":"142.251.14.95","error":null,"status":"resolved"},"ayidna-dashboard.pages.dev":{"ip":"188.114.96.3","error":null,"status":"resolved"}},"total_responses":3,"domains_contacted":["fonts.googleapis.com","ayidna-dashboard.pages.dev"],"http_transactions":[{"request":{"url":"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==","type":"Image","method":"GET","headers":{"Pragma":"no-cache","Referer":"","Cache-Control":"no-cache, no-store, must-revalidate"}},"response":{"url":"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==","status":200,"headers":{"Content-Type":"image/gif"},"mimeType":"image/gif","protocol":"data","statusText":"OK","securityState":"unknown","remoteIPAddress":null,"encodedDataLength":0.0},"duration_ms":null},{"request":{"url":"https://ayidna-dashboard.pages.dev/","type":"Document","method":"GET","headers":{"Pragma":"no-cache","Cache-Control":"no-cache, no-store, must-revalidate","Upgrade-Insecure-Requests":"1"}},"response":{"url":"https://ayidna-dashboard.pages.dev/","status":200,"headers":{"nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Wed, 12 Aug 2026 08:17:08 GMT","cf-ray":"a29e0aba8de735a6-OSL","server":"cloudflare","alt-svc":"h3=\":443\"; ma=86400","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=enagq3eUgxjiR%2B%2FHsgAaOCFFG0YYQPwf1866kxa6BbB4uqbXKy5XnsdE%2FiFcw3HC5LL27urBYykNPfWLQ1c3Ud4LNQWukPJSM9RVC4nBwZibkYrjTCqEbVH52FIz1j1M85XOnnSNQBUw3%2Bjxbw%3D%3D\"}]}","content-type":"text/html; charset=utf-8","cache-control":"public, max-age=0, must-revalidate","referrer-policy":"strict-origin-when-cross-origin","content-encoding":"br","x-content-type-options":"nosniff","access-control-allow-origin":"*"},"mimeType":"text/html","protocol":"h2","statusText":"","securityState":"secure","remoteIPAddress":"","encodedDataLength":41071.0},"duration_ms":null}],"performance_metrics":{"request_count":2,"total_duration":null,"fastest_request":null,"slowest_request":null,"average_request_duration":null}},"local_storage":[],"session_storage":[],"domain_description":"Within the developer-focused generic top-level domain (.dev), 'ayidna-dashboard.pages.dev' is registered and includes subdomain 'ayidna-dashboard'. The core label 'pages' covers 5 characters split between 2 vowels and 3 consonants. It segments into one word: pages. No strong language cues emerged from the frequency lists.","bot_detection":null,"capture_recovered":false,"recovered_capture_refused":null,"navigation_committed":true,"site_not_reached":null,"dns_not_found_host":null,"title_source":"regular","screenshot_version":null,"warning_page_detected":false,"warning_page_type":null,"warning_page_url":null,"extracted_target_url":null,"warning_bypass_successful":null,"warning_bypass_load_time":null,"sections_available":{"malware":false,"yara":false,"reports":false},"compacted":null,"verdicts_ready":true,"warning_bypass_error":null,"ocr_text":"Bienvenue\n\nConnectez-vous 8 vatre espace\n\nBloqué ? Réinitialiser\n","javascript_files":[{"url":"inline://22375397-1a27-454d-9187-41578701c6d8/script_0_6764c569c9d4bbd2","filename":null,"script_type":"inline","content_sha256":"6764c569c9d4bbd2b6638031f10b27e3d25224bb808083a5d55261bbca64f0f9","is_whitelisted":false,"metrics":{"code_length":89607,"normalized_length":73476,"function_count":282,"function_call_count":797,"ast_node_count":13928,"ast_depth":25,"url_count":43,"domain_count":null,"fuzzy_block_size":0,"module_count":0,"complexity_score":288},"ml_vectors":{"available":true,"codebert_available":false,"graphcodebert_available":false,"ast_features_available":true,"handcrafted_features_available":true,"composite_vector_available":true,"dimensions":{"codebert":768,"graphcodebert":768,"ast_features":128,"handcrafted":64,"composite":192}},"library_detection":{"detected":false,"primary_library":"","version":"","confidence":{},"all_libraries":[],"library_count":0},"copyright":{"authors":[],"licenses":[],"versions":[],"library_names":[],"copyright_count":0,"detected_library":null,"copyright_notices":[],"signature_matches":[],"retirejs_detection":null,"multiple_copyrights":false},"module_info":{"pattern":"script","is_module":false,"import_count":0,"detected_modules":[]},"cdn_info":{"is_cdn":false,"cdn_type":null,"is_minified_url":false}}],"url_metadata":{"is_redirect_wrapper":false,"wrapper_type":null,"extracted_destination":null,"fragment_data":null,"original_url":"https://ayidna-dashboard.pages.dev/"},"parent_scan_id":null,"scan_relationship":null,"child_scans":[],"ioc_matches":null}