
// === Theme toggle (persisted) ===
(function(){
  const root = document.documentElement;
  const saved = localStorage.getItem('theme');
  if (saved) { root.setAttribute('data-theme', saved); } else { root.setAttribute('data-theme', 'light'); }
}
  document.addEventListener('click', (e)=>{
    const btn = e.target.closest('[data-theme-toggle]');
    if(!btn) return;
    const curr = root.getAttribute('data-theme') === 'light' ? 'dark' : 'light';
    root.setAttribute('data-theme', curr);
    localStorage.setItem('theme', curr);
    btn.textContent = curr === 'light' ? (btn.dataset.labelLight || '☀️ Light') : (btn.dataset.labelDark || '🌙 Dark');
  });
  // Initialize label on load
  document.addEventListener('DOMContentLoaded', ()=>{
    const btn = document.querySelector('[data-theme-toggle]');
    if(!btn) return;
    const isLight = root.getAttribute('data-theme') === 'light';
    btn.textContent = isLight ? (btn.dataset.labelLight || '☀️ Light') : (btn.dataset.labelDark || '🌙 Dark');
  });
})();

// === Safer contact fetch: handle non-JSON and HTTP errors ===
async function postFormJSON(url, formData){
  const resp = await fetch(url, { method:'POST', body: formData });
  let data = null;
  try {
    data = await resp.json();
  } catch (e) {
    // Not JSON; fall back
    data = { ok:false, msg: 'الاستضافة أعادت استجابة غير صالحة (غير JSON). الكود: ' + resp.status };
  }
  if(!resp.ok && data && !data.msg){
    data.msg = 'خطأ HTTP: ' + resp.status;
  }
  return data;
}


// Simple Lightbox for gallery
document.addEventListener('click', function(e){
  const a = e.target.closest('[data-lightbox]');
  if(!a) return;
  e.preventDefault();
  const src = a.getAttribute('href');
  const overlay = document.createElement('div');
  overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.85);display:flex;align-items:center;justify-content:center;z-index:9999;';
  const img = document.createElement('img');
  img.src = src;
  img.style.maxWidth = '92%';
  img.style.maxHeight = '92%';
  img.style.boxShadow = '0 10px 40px rgba(0,0,0,.6)';
  img.style.borderRadius = '12px';
  overlay.appendChild(img);
  overlay.addEventListener('click', ()=> overlay.remove());
  document.body.appendChild(overlay);
});

// Dynamic year
const yearEl = document.querySelectorAll('[data-year]');
yearEl.forEach(e=> e.textContent = new Date().getFullYear());


// Contact form submit (AJAX)
document.addEventListener('submit', async (e)=>{
  const form = e.target.closest('#contact-form');
  if(!form) return;
  e.preventDefault();
  const status = document.getElementById('contact-status');
  if(status) status.innerHTML = '';
  const data = new FormData(form);
  try{
    const result = await postFormJSON('contact.php', data);
    if(result && result.ok){
      if(status) status.innerHTML = '<div class="alert success">تم الاستلام بنجاح.</div>';
      form.reset();
    }else{
      const msg = result && result.msg ? result.msg : 'تعذّر إرسال الرسالة، حاول لاحقًا.';
      if(status) status.innerHTML = '<div class="alert error">' + msg + '</div>';
    }
  }catch(err){
    if(status) status.innerHTML = '<div class="alert error">تعذر الاتصال بالخادم.</div>';
  }
});
    const result = await resp.json();
    if(result && result.ok){
      status.innerHTML = '<div class="alert success">تم استلام رسالتك، سنعاود الاتصال بك قريبًا.</div>';
      form.reset();
    }else{
      status.innerHTML = '<div class="alert error">' + (result && result.msg ? result.msg : 'تعذّر إرسال الرسالة، حاول لاحقًا.') + '</div>';
    }
  }catch(err){
    status.innerHTML = '<div class="alert error">حدث خطأ غير متوقع. حاول لاحقًا.</div>';
  }
});

// /*defensive-init*/ ensure label updates even if DOMContentLoaded fired earlier
(function(){
  const root = document.documentElement;
  function setLabel(){
    const btn = document.querySelector('[data-theme-toggle]');
    if(!btn) return;
    const isLight = (root.getAttribute('data-theme') || 'light') === 'light';
    btn.textContent = isLight ? (btn.dataset.labelLight || '☀️ Light') : (btn.dataset.labelDark || '🌙 Dark');
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setLabel);
  } else {
    setLabel();
  }
})();
