(() => {
  const $ = (sel, root = document) => root.querySelector(sel);
  const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));

  $$('[data-tab]').forEach(tab => tab.addEventListener('click', () => {
    const target = tab.dataset.tab;
    $$('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === target));
    $$('.tab-panel').forEach(panel => panel.classList.toggle('active', panel.dataset.panel === target));
  }));

  let deferredPrompt = null;
  const installBtn = $('#installBtn');
  window.addEventListener('beforeinstallprompt', event => {
    event.preventDefault();
    deferredPrompt = event;
    if (installBtn) installBtn.hidden = false;
  });
  if (installBtn) {
    installBtn.addEventListener('click', async () => {
      if (!deferredPrompt) return;
      deferredPrompt.prompt();
      await deferredPrompt.userChoice;
      deferredPrompt = null;
      installBtn.hidden = true;
    });
  }

  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => navigator.serviceWorker.register('service-worker.js').catch(() => {}));
  }

  window.setQuickTime = function(minutes) {
    const start = document.querySelector('input[name="start"]');
    if (!start) return;
    const date = new Date(Date.now() + minutes * 60000);
    start.value = toLocalDatetime(date);
  };
  window.setTodayEvening = function() {
    const start = document.querySelector('input[name="start"]');
    if (!start) return;
    const date = new Date();
    date.setHours(19, 0, 0, 0);
    start.value = toLocalDatetime(date);
  };
  window.setTomorrowMorning = function() {
    const start = document.querySelector('input[name="start"]');
    if (!start) return;
    const date = new Date(Date.now() + 24 * 60 * 60000);
    date.setHours(9, 0, 0, 0);
    start.value = toLocalDatetime(date);
  };
  function toLocalDatetime(date) {
    const pad = n => String(n).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
  }

  $$('.member-filter').forEach(btn => btn.addEventListener('click', () => {
    const member = btn.dataset.memberFilter;
    $$('.member-filter').forEach(b => b.classList.toggle('active', b === btn));
    $$('.filter-targets [data-member]').forEach(card => card.hidden = member !== 'all' && card.dataset.member !== member);
  }));
  $$('.filter').forEach(btn => btn.addEventListener('click', () => {
    const type = btn.dataset.listFilter;
    $$('.filter').forEach(b => b.classList.toggle('active', b === btn));
    $$('.list-targets [data-list-type]').forEach(row => row.hidden = type !== 'all' && row.dataset.listType !== type);
  }));


  function closeMealPickers(except = null) {
    $$('[data-meal-picker].is-open').forEach(picker => {
      if (picker === except) return;
      picker.classList.remove('is-open');
      const trigger = picker.querySelector('[data-meal-trigger]');
      if (trigger) trigger.setAttribute('aria-expanded', 'false');
    });
  }

  $$('[data-meal-picker]').forEach(picker => {
    const trigger = picker.querySelector('[data-meal-trigger]');
    const input = picker.querySelector('[data-meal-input]');
    const img = picker.querySelector('[data-meal-img]');
    const title = picker.querySelector('[data-meal-title]');
    if (!trigger || !input) return;

    trigger.addEventListener('click', event => {
      event.stopPropagation();
      if (trigger.disabled) return;
      const open = picker.classList.contains('is-open');
      closeMealPickers(open ? null : picker);
      picker.classList.toggle('is-open', !open);
      trigger.setAttribute('aria-expanded', String(!open));
    });

    picker.querySelectorAll('[data-meal-id]').forEach(option => {
      option.addEventListener('click', event => {
        event.preventDefault();
        event.stopPropagation();
        input.value = option.dataset.mealId || '';
        if (img && option.dataset.img) img.src = option.dataset.img;
        if (title && option.dataset.title) title.textContent = option.dataset.title;
        picker.querySelectorAll('[data-meal-id]').forEach(o => {
          const selected = o === option;
          o.classList.toggle('active', selected);
          o.setAttribute('aria-selected', String(selected));
        });
        closeMealPickers();
      });
    });
  });
  document.addEventListener('click', () => closeMealPickers());
  document.addEventListener('keydown', event => { if (event.key === 'Escape') closeMealPickers(); });

  const clock = $('#liveClock');
  if (clock) {
    setInterval(() => {
      clock.textContent = new Date().toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
    }, 15000);
  }

  let idleTimer;
  function resetIdle() {
    document.body.classList.remove('idle-mode');
    clearTimeout(idleTimer);
    idleTimer = setTimeout(() => document.body.classList.add('idle-mode'), 120000);
  }
  ['mousemove','keydown','touchstart','click'].forEach(type => window.addEventListener(type, resetIdle, {passive:true}));
  resetIdle();
})();
// v6.2 registration Family Hub choice toggle
(() => {
  const modeInputs = Array.from(document.querySelectorAll('[data-family-hub-mode]'));
  const panels = Array.from(document.querySelectorAll('[data-family-hub-panel]'));
  if (!modeInputs.length || !panels.length) return;
  const sync = () => {
    const selected = (modeInputs.find(input => input.checked) || modeInputs[0]).value;
    panels.forEach(panel => {
      const active = panel.dataset.familyHubPanel === selected;
      panel.hidden = !active;
      panel.querySelectorAll('input, select, textarea').forEach(field => {
        if (field.name === 'family_hub_code') field.required = active && selected === 'join';
      });
    });
  };
  modeInputs.forEach(input => input.addEventListener('change', sync));
  sync();
})();

// v6.4 notification bell with 30-minute reminder alarm sound
(() => {
  const bell = document.getElementById('notificationBell');
  const panel = document.getElementById('notificationPanel');
  if (!bell || !panel) return;

  function playAlarm() {
    try {
      const AudioContext = window.AudioContext || window.webkitAudioContext;
      if (!AudioContext) return;
      const ctx = new AudioContext();
      const master = ctx.createGain();
      master.gain.value = 0.08;
      master.connect(ctx.destination);
      [0, 0.18, 0.36].forEach((offset) => {
        const osc = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.type = 'sine';
        osc.frequency.setValueAtTime(880, ctx.currentTime + offset);
        osc.frequency.exponentialRampToValueAtTime(660, ctx.currentTime + offset + 0.12);
        gain.gain.setValueAtTime(0, ctx.currentTime + offset);
        gain.gain.linearRampToValueAtTime(1, ctx.currentTime + offset + 0.02);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + offset + 0.16);
        osc.connect(gain);
        gain.connect(master);
        osc.start(ctx.currentTime + offset);
        osc.stop(ctx.currentTime + offset + 0.18);
      });
      setTimeout(() => ctx.close().catch(() => {}), 900);
    } catch (_) {}
  }


  let armed = false;
  const hasDueSoon = Boolean(bell.querySelector('b'));
  function armReminderAudio() {
    if (armed) return;
    armed = true;
    if (hasDueSoon && panel.hidden) playAlarm();
  }
  ['click', 'touchstart', 'keydown'].forEach(type => window.addEventListener(type, armReminderAudio, { once: true, passive: true }));

  function setOpen(open) {
    panel.hidden = !open;
    panel.classList.toggle('is-open', open);
    bell.setAttribute('aria-expanded', String(open));
    if (open) playAlarm();
  }

  bell.addEventListener('click', (event) => {
    event.stopPropagation();
    setOpen(panel.hidden);
  });
  panel.addEventListener('click', event => event.stopPropagation());
  document.addEventListener('click', () => setOpen(false));
  document.addEventListener('keydown', event => { if (event.key === 'Escape') setOpen(false); });
})();


// v6.5 local login theme toggle + browser privacy restrictions
(() => {
  const KEY = 'homesynchub-local-theme';
  const root = document.documentElement;
  const btn = document.querySelector('[data-local-theme-toggle]');
  const apply = (theme) => {
    if (!theme) return;
    root.setAttribute('data-theme', theme);
    if (btn) btn.textContent = theme === 'light' ? '🌙 Dark' : '☀️ Light';
  };
  apply(localStorage.getItem(KEY) || root.getAttribute('data-theme') || 'dark');
  if (btn) btn.addEventListener('click', () => {
    const next = root.getAttribute('data-theme') === 'light' ? 'dark' : 'light';
    localStorage.setItem(KEY, next);
    apply(next);
  });
})();

(() => {
  document.addEventListener('contextmenu', event => event.preventDefault());
  document.addEventListener('dragstart', event => event.preventDefault());

  let shield = null;
  function getShield() {
    if (shield) return shield;
    shield = document.createElement('div');
    shield.className = 'privacy-screen-shield';
    shield.innerHTML = '<div><strong>Privacy Protected</strong><span>Screenshots, printing, and right-click actions are restricted in this browser session.</span></div>';
    document.body.appendChild(shield);
    return shield;
  }
  function showShield(ms = 900) {
    const node = getShield();
    node.classList.add('is-active');
    window.setTimeout(() => node.classList.remove('is-active'), ms);
  }
  document.addEventListener('keydown', event => {
    const key = String(event.key || '').toLowerCase();
    const blocked = key === 'printscreen' ||
      ((event.ctrlKey || event.metaKey) && ['p','s','u'].includes(key)) ||
      ((event.ctrlKey || event.metaKey) && event.shiftKey && ['i','j','c','s'].includes(key));
    if (!blocked) return;
    event.preventDefault();
    event.stopPropagation();
    try { navigator.clipboard && navigator.clipboard.writeText(''); } catch (_) {}
    showShield(key === 'printscreen' ? 1200 : 900);
  }, true);
  window.addEventListener('beforeprint', () => showShield(1400));
})();

// v6.6 stronger browser-level capture deterrents.
(() => {
  const getShield = () => {
    let shield = document.querySelector('.privacy-screen-shield');
    if (!shield) {
      shield = document.createElement('div');
      shield.className = 'privacy-screen-shield';
      shield.innerHTML = '<div><strong>Privacy Protected</strong><span>Screen capture, recording, printing, right-click, copy, and developer shortcuts are restricted in this browser session.</span></div>';
      document.body.appendChild(shield);
    }
    return shield;
  };
  const flashShield = (ms = 1100) => {
    const shield = getShield();
    document.body.classList.add('privacy-blur');
    shield.classList.add('is-active');
    window.setTimeout(() => {
      shield.classList.remove('is-active');
      document.body.classList.remove('privacy-blur');
    }, ms);
  };
  ['copy', 'cut'].forEach(type => document.addEventListener(type, event => {
    const target = event.target;
    if (target && ['INPUT', 'TEXTAREA'].includes(target.tagName)) return;
    event.preventDefault();
    flashShield(800);
  }, true));
  window.addEventListener('blur', () => {
    document.body.classList.add('privacy-blur');
  });
  window.addEventListener('focus', () => {
    document.body.classList.remove('privacy-blur');
  });
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) document.body.classList.add('privacy-blur');
    else {
      document.body.classList.remove('privacy-blur');
      flashShield(650);
    }
  });
  document.addEventListener('keyup', event => {
    if (String(event.key || '').toLowerCase() === 'printscreen') {
      try { navigator.clipboard && navigator.clipboard.writeText(''); } catch (_) {}
      flashShield(1300);
    }
  }, true);
})();

// v6.8.1 corrected Profile dropdown beside Mobile/Desktop view toggle
(() => {
  const button = document.getElementById('profileTopButton');
  const panel = document.getElementById('profileDropdownPanel');
  if (!button || !panel) return;
  const setOpen = (open) => {
    panel.hidden = !open;
    panel.classList.toggle('is-open', open);
    button.setAttribute('aria-expanded', String(open));
  };
  button.addEventListener('click', (event) => {
    event.stopPropagation();
    setOpen(panel.hidden);
  });
  panel.addEventListener('click', event => event.stopPropagation());
  document.addEventListener('click', () => setOpen(false));
  document.addEventListener('keydown', event => { if (event.key === 'Escape') setOpen(false); });
})();


// v7.0 mobile sidebar toggle for rebuilt dashboard shell
(() => {
  const toggle = document.querySelector('.sidebar-toggle-ref');
  if (!toggle) return;
  toggle.addEventListener('click', () => document.body.classList.toggle('sidebar-open'));
  document.addEventListener('click', (event) => {
    if (!document.body.classList.contains('sidebar-open')) return;
    if (event.target.closest('.dashboard-ref-sidebar') || event.target.closest('.sidebar-toggle-ref')) return;
    document.body.classList.remove('sidebar-open');
  });
})();


// v7.2 Add New modal: type-aware grouping and placeholders.
(() => {
  const form = document.querySelector('[data-add-new-form]');
  if (!form) return;
  const radios = Array.from(form.querySelectorAll('input[name="type"]'));
  const titleInput = form.querySelector('[data-title-input]');
  const categoryInput = form.querySelector('[data-category-input]');
  const notesInput = form.querySelector('[data-notes-input]');
  const mealSlot = form.querySelector('select[name="meal_slot"]');
  const pointInput = form.querySelector('input[name="points"]');
  const starInput = form.querySelector('input[name="stars"]');
  const examples = {
    task: { title: 'Example: Review school bag, Pay bill, Prepare documents', category: 'Home, School, Personal', notes: 'Add checklist details, reminders, or shared instructions.' },
    chore: { title: 'Example: Clean kitchen, Take out trash, Fold laundry', category: 'Home, Cleaning, Routine', notes: 'Add chore rules, approval notes, or reward conditions.' },
    event: { title: 'Example: Family dinner, Soccer practice, Doctor appointment', category: 'Family, School, Appointment', notes: 'Add agenda, invite details, or event notes.' },
    meal: { title: 'Example: Chicken Adobo dinner, Tapsilog breakfast', category: 'Breakfast, Lunch, Dinner, Snacks', notes: 'Add ingredients line by line to build grocery ideas.' }
  };
  function sync() {
    const type = (radios.find(r => r.checked) || radios[0]).value;
    form.dataset.itemType = type;
    form.querySelectorAll('[data-show-for]').forEach(node => {
      const allowed = String(node.dataset.showFor || '').split(/\s+/).filter(Boolean);
      const show = allowed.includes(type);
      node.hidden = !show;
      node.querySelectorAll('input,select,textarea').forEach(control => {
        control.disabled = !show;
      });
    });
    if (titleInput) titleInput.placeholder = examples[type].title;
    if (categoryInput) categoryInput.placeholder = examples[type].category;
    if (notesInput) notesInput.placeholder = examples[type].notes;
    if (mealSlot && type === 'meal' && mealSlot.value === '') mealSlot.value = 'Dinner';
    if (pointInput && !pointInput.value) pointInput.value = type === 'event' ? '0' : '10';
    if (starInput && !starInput.value) starInput.value = type === 'chore' ? '1' : '0';
  }
  radios.forEach(radio => radio.addEventListener('change', sync));
  const dialog = document.getElementById('addModal');
  if (dialog) dialog.addEventListener('close', () => window.setTimeout(sync, 0));
  sync();
})();

// v7.6 Floating Joshleen AI chatbox and global search shortcut.
(() => {
  const aiPanel = document.getElementById('joshleenAiPanel');
  const aiToggles = Array.from(document.querySelectorAll('[data-ai-toggle]'));
  const closeButtons = Array.from(document.querySelectorAll('[data-ai-close]'));
  const minimizeButtons = Array.from(document.querySelectorAll('[data-ai-minimize]'));
  const messages = aiPanel ? aiPanel.querySelector('[data-ai-messages]') : null;
  const form = aiPanel ? aiPanel.querySelector('[data-ai-form]') : null;
  const input = form ? form.querySelector('input[name="message"]') : null;
  const prompts = Array.from(document.querySelectorAll('[data-ai-prompt]'));

  if (aiPanel && aiToggles.length) {
    const setOpen = (open) => {
      document.body.classList.toggle('ai-panel-open', open);
      aiPanel.hidden = !open;
      aiPanel.classList.toggle('is-open', open);
      if (!open) aiPanel.classList.remove('is-minimized');
      aiToggles.forEach(btn => btn.setAttribute('aria-expanded', String(open)));
      if (open && input) window.setTimeout(() => input.focus(), 120);
    };
    const appendMessage = (role, text, icon) => {
      if (!messages) return;
      const article = document.createElement('article');
      article.className = `ai-msg ${role}`;
      const avatar = document.createElement('span');
      avatar.textContent = icon || (role === 'user' ? '👤' : '🤖');
      const bubble = document.createElement('p');
      bubble.textContent = text;
      article.append(avatar, bubble);
      messages.appendChild(article);
      messages.scrollTop = messages.scrollHeight;
    };
    const replyFor = (text) => {
      const q = text.toLowerCase();
      if (q.includes('30') || q.includes('due') || q.includes('remind')) return 'I can help check upcoming items and reminder timing. In HomeSyncHub, the notification bell highlights items due soon, with the default reminder window set to 30 minutes.';
      if (q.includes('todo') || q.includes('task') || q.includes('chore')) return 'I can help create a Todo item. Use + Add New, choose Task or Chore, assign points/stars, then save. Press Done later to release the reward once.';
      if (q.includes('meal') || q.includes('dinner') || q.includes('grocery')) return 'I can help plan meals. Open Meals to choose from the meal planner, then use Grocery List to collect ingredients from planned meals.';
      if (q.includes('reward') || q.includes('point') || q.includes('star')) return 'Rewards are released when eligible Todo items are completed. Completed items update points, stars, history, and reward progress.';
      if (q.includes('calendar') || q.includes('event') || q.includes('schedule')) return 'I can guide you to create or review calendar items. Use Calendar for Day, Week, Month, or Agenda views, or + Add New to create an event.';
      if (q.includes('family') || q.includes('hub') || q.includes('workspace')) return 'Family Hub data is isolated per hub. Use the Profile dropdown to switch hubs, manage Family Hubs, or access Sync and Rewards.';
      return 'I can help with Calendar, Todo List, Meals, Rewards, reminders, and Family Hub actions. I will guide or draft the action first so you can confirm before saving.';
    };
    const submitMessage = (text) => {
      const clean = String(text || '').trim();
      if (!clean) return;
      setOpen(true);
      aiPanel.classList.remove('is-minimized');
      appendMessage('user', clean, '👤');
      if (input) input.value = '';
      const typing = document.createElement('article');
      typing.className = 'ai-msg bot typing';
      typing.innerHTML = '<span>🤖</span><p>Joshleen AI is typing…</p>';
      messages.appendChild(typing);
      messages.scrollTop = messages.scrollHeight;
      window.setTimeout(() => {
        typing.remove();
        appendMessage('bot', replyFor(clean), '🤖');
      }, 420);
    };

    aiToggles.forEach(btn => btn.addEventListener('click', () => setOpen(!document.body.classList.contains('ai-panel-open'))));
    closeButtons.forEach(btn => btn.addEventListener('click', () => setOpen(false)));
    minimizeButtons.forEach(btn => btn.addEventListener('click', () => {
      aiPanel.classList.toggle('is-minimized');
    }));
    if (form) form.addEventListener('submit', (event) => {
      event.preventDefault();
      submitMessage(input ? input.value : '');
    });
    prompts.forEach(btn => btn.addEventListener('click', () => submitMessage(btn.getAttribute('data-ai-prompt') || btn.textContent || '')));
    document.addEventListener('keydown', event => { if (event.key === 'Escape') setOpen(false); });
  }

  const search = document.querySelector('.global-search input[name="q"]');
  if (search) {
    document.addEventListener('keydown', event => {
      if ((event.ctrlKey || event.metaKey) && String(event.key).toLowerCase() === 'k') {
        event.preventDefault();
        search.focus();
        search.select();
      }
    });
  }
})();
