(function(){
  const form = document.getElementById('footerForm');
  const msg = document.getElementById('footerMsg');
  const footerPreview = document.getElementById('footerPreview');
  const headerPreview = document.getElementById('headerPreview');
  const saveTop = document.getElementById('saveFooterTopBtn');
  const previewBtn = document.getElementById('previewFooterBtn');
  const logoInput = form ? form.elements.header_logo_image : null;
  if (!form) return;

  let uploadedLogoPreviewUrl = '';
  let savedLogoPath = '';

  const fields = [
    'header_logo_text', 'header_admin_brand_name', 'header_client_brand_name', 'header_subtitle', 'header_remove_logo',
    'footer_enabled', 'footer_logo_text', 'footer_brand_name', 'footer_tagline',
    'footer_description', 'footer_address', 'footer_phone', 'footer_email',
    'footer_whatsapp_url', 'footer_instagram_url', 'footer_facebook_url',
    'footer_copyright', 'footer_show_quick_links', 'footer_show_contact',
    'footer_show_social', 'footer_accent_note'
  ];

  function esc(value) {
    return String(value ?? '').replace(/[&<>'"]/g, c => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', "'":'&#39;', '"':'&quot;'}[c]));
  }

  function formDataObject() {
    const data = {};
    fields.forEach(name => {
      const el = form.elements[name];
      if (!el) return;
      if (el.type === 'checkbox') data[name] = el.checked ? '1' : '0';
      else data[name] = el.value || '';
    });
    data.header_logo_image_path = savedLogoPath || '';
    return data;
  }

  function fillForm(settings) {
    savedLogoPath = settings.header_logo_image_path || '';
    fields.forEach(name => {
      const el = form.elements[name];
      if (!el) return;
      if (el.type === 'checkbox') el.checked = String(settings[name] ?? '0') === '1';
      else el.value = settings[name] ?? '';
    });
    if (form.elements.header_remove_logo) form.elements.header_remove_logo.checked = false;
  }

  function logoMarkup(settings) {
    const removeLogo = String(settings.header_remove_logo || '0') === '1';
    const path = removeLogo ? '' : (uploadedLogoPreviewUrl || (settings.header_logo_image_path ? '../' + String(settings.header_logo_image_path).replace(/^\/+/, '') : ''));
    if (path) return `<img src="${esc(path)}" alt="Logo">`;
    return esc((settings.header_logo_text || 'PY').slice(0, 6).toUpperCase());
  }

  function renderHeaderPreview(settings) {
    const adminName = settings.header_admin_brand_name || 'Pyrk Admin';
    const clientName = settings.header_client_brand_name || 'Pyrk';
    const subtitle = settings.header_subtitle || 'Walking Club';

    const smallMark = document.getElementById('headerLogoPreviewMark');
    const adminText = document.getElementById('headerAdminNamePreview');
    const subText = document.getElementById('headerSubtitlePreview');
    if (smallMark) smallMark.innerHTML = logoMarkup(settings);
    if (adminText) adminText.textContent = adminName;
    if (subText) subText.textContent = subtitle;

    if (!headerPreview) return;
    headerPreview.innerHTML = `
      <div class="header-preview-bar">
        <div class="header-preview-brand">
          <span class="header-preview-logo">${logoMarkup(settings)}</span>
          <div><strong>${esc(adminName)}</strong><small>${esc(subtitle)}</small></div>
        </div>
        <span class="nav-action-pill">Client Portal</span>
        <span class="user-chip mini"><span>N</span><div><strong>Admin User</strong><small>super admin</small></div></span>
      </div>
      <div class="header-preview-bar client-preview">
        <div class="header-preview-brand">
          <span class="header-preview-logo">${logoMarkup(settings)}</span>
          <div><strong>${esc(clientName)}</strong><small>${esc(subtitle)}</small></div>
        </div>
        <span class="nav-action-pill">Admin Portal</span>
        <span class="user-chip mini"><span>M</span><div><strong>Member User</strong><small>member</small></div></span>
      </div>`;
  }

  function renderFooterPreview(settings) {
    if (!footerPreview) return;
    if (String(settings.footer_enabled || '1') !== '1') {
      footerPreview.innerHTML = '<div class="notice bad" style="margin:20px">Footer is currently disabled.</div>';
      return;
    }
    const year = new Date().getFullYear();
    const copyright = String(settings.footer_copyright || '© {year} Pyrk Walking Club. All rights reserved.').replace('{year}', year);
    const socialLinks = [
      settings.footer_instagram_url ? `<a href="#">Instagram</a>` : '',
      settings.footer_facebook_url ? `<a href="#">Facebook</a>` : '',
      settings.footer_whatsapp_url ? `<a href="#">WhatsApp</a>` : ''
    ].filter(Boolean).join('') || '<span>Add social links from Admin → Branding & footer.</span>';

    footerPreview.innerHTML = `
      <footer class="pyrk-footer" aria-label="Footer preview">
        <div class="pyrk-footer-shell">
          <section class="pyrk-footer-brand">
            <div class="pyrk-footer-logo-row">
              <span class="pyrk-footer-logo">${esc(settings.footer_logo_text || 'PY')}</span>
              <div><strong>${esc(settings.footer_brand_name || 'Pyrk Walking Club')}</strong><small>${esc(settings.footer_tagline || '')}</small></div>
            </div>
            <p>${esc(settings.footer_description || '')}</p>
            ${settings.footer_accent_note ? `<div class="pyrk-footer-note">${esc(settings.footer_accent_note)}</div>` : ''}
          </section>
          ${String(settings.footer_show_quick_links || '1') === '1' ? `<section class="pyrk-footer-col"><h3>Quick links</h3><a href="#">Client dashboard</a><a href="#">My QR code</a><a href="#">Upcoming walks</a></section>` : ''}
          ${String(settings.footer_show_contact || '1') === '1' ? `<section class="pyrk-footer-col"><h3>Contact</h3>${settings.footer_address ? `<span>${esc(settings.footer_address)}</span>` : ''}${settings.footer_phone ? `<a href="#">${esc(settings.footer_phone)}</a>` : ''}${settings.footer_email ? `<a href="#">${esc(settings.footer_email)}</a>` : ''}<a class="pyrk-footer-manage" href="#">Manage branding</a></section>` : ''}
          ${String(settings.footer_show_social || '1') === '1' ? `<section class="pyrk-footer-col"><h3>Social</h3><div class="pyrk-footer-socials">${socialLinks}</div></section>` : ''}
        </div>
        <div class="pyrk-footer-bottom"><span>${esc(copyright)}</span><span>Built for safe walks, check-ins, loyalty, and community memories.</span></div>
      </footer>`;
  }

  function renderPreview(settings) {
    renderHeaderPreview(settings);
    renderFooterPreview(settings);
  }

  async function loadSettings() {
    const res = await Pyrk.get('footer.php', {action: 'settings'});
    if (!res.ok) {
      if (msg) { msg.className = 'notice bad'; msg.textContent = res.message || 'Could not load settings.'; }
      return;
    }
    const settings = res.data.settings || {};
    fillForm(settings);
    renderPreview(settings);
  }

  async function saveSettings(event) {
    if (event) event.preventDefault();
    const previewData = formDataObject();
    renderPreview(previewData);
    if (msg) { msg.className = 'notice'; msg.textContent = 'Saving...'; }

    const fd = new FormData(form);
    fd.set('action', 'save');
    if (!form.elements.header_remove_logo || !form.elements.header_remove_logo.checked) {
      fd.set('header_remove_logo', '0');
    }

    const res = Pyrk.postForm
      ? await Pyrk.postForm('footer.php', fd)
      : await fetch(Pyrk.url('footer.php'), {method: 'POST', credentials: 'same-origin', headers: {'X-CSRF-Token': Pyrk.csrf || ''}, body: fd}).then(r => r.json()).catch(e => ({ok:false,message:e.message}));

    if (msg) { msg.className = 'notice ' + (res.ok ? 'ok' : 'bad'); msg.textContent = res.message || (res.ok ? 'Saved.' : 'Save failed.'); }
    if (res.ok && res.data && res.data.settings) {
      uploadedLogoPreviewUrl = '';
      if (logoInput) logoInput.value = '';
      fillForm(res.data.settings);
      renderPreview(res.data.settings);
    }
  }

  function updateUploadedLogoPreview() {
    const file = logoInput && logoInput.files ? logoInput.files[0] : null;
    if (!file) {
      uploadedLogoPreviewUrl = '';
      renderPreview(formDataObject());
      return;
    }
    const reader = new FileReader();
    reader.onload = () => {
      uploadedLogoPreviewUrl = reader.result || '';
      if (form.elements.header_remove_logo) form.elements.header_remove_logo.checked = false;
      renderPreview(formDataObject());
    };
    reader.readAsDataURL(file);
  }

  form.addEventListener('submit', saveSettings);
  if (saveTop) saveTop.addEventListener('click', saveSettings);
  if (previewBtn) previewBtn.addEventListener('click', () => renderPreview(formDataObject()));
  form.addEventListener('input', () => renderPreview(formDataObject()));
  form.addEventListener('change', () => renderPreview(formDataObject()));
  if (logoInput) logoInput.addEventListener('change', updateUploadedLogoPreview);
  document.addEventListener('DOMContentLoaded', loadSettings);
  loadSettings();
})();
