(() => {
  'use strict';

  const state = {
    profile: null,
    dirty: false,
    previewUrl: null,
    canEditOwnProfile: true,
  };

  const byId = id => document.getElementById(id);
  const text = (id, value) => { const el = byId(id); if (el) el.textContent = value ?? ''; };
  const value = (id, next) => { const el = byId(id); if (el) el.value = next ?? ''; };

  function initials(name) {
    const parts = String(name || 'P').trim().split(/\s+/).filter(Boolean);
    return (parts.slice(0, 2).map(part => part.charAt(0)).join('') || 'P').toUpperCase();
  }

  function splitName(fullName) {
    const parts = String(fullName || '').trim().split(/\s+/).filter(Boolean);
    return {
      first: parts.shift() || '',
      last: parts.join(' '),
    };
  }

  function assetPath(path) {
    return String(path || '').replace(/^\/+/, '');
  }

  function setAvatar(elementId, profile, previewPath = '') {
    const el = byId(elementId);
    if (!el) return;
    const path = previewPath || profile?.profile_photo_path || '';
    if (path) {
      el.innerHTML = `<img src="${Pyrk.esc(assetPath(path))}" alt="${Pyrk.esc(profile?.full_name || 'Member')} profile photo">`;
    } else {
      el.textContent = initials(profile?.full_name);
    }
  }

  function statusLabel(status) {
    const clean = String(status || 'active').replace(/_/g, ' ');
    return clean.charAt(0).toUpperCase() + clean.slice(1);
  }

  function genderLabel(gender) {
    if (!gender) return 'Not provided';
    return String(gender).replace(/_/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
  }

  function completeness(profile) {
    const checks = [
      ['Profile photo', Boolean(profile.profile_photo_path)],
      ['Name', Boolean(String(profile.full_name || '').trim())],
      ['Email', Boolean(String(profile.email || '').trim())],
      ['Mobile number', Boolean(String(profile.mobile || '').trim())],
      ['Date of birth', Boolean(profile.date_of_birth)],
      ['Emergency contact', Boolean(String(profile.emergency_contact_name || '').trim())],
      ['Emergency mobile', Boolean(String(profile.emergency_contact_mobile || '').trim())],
    ];
    const complete = checks.filter(([, ready]) => ready).length;
    return {checks, percent: Math.round((complete / checks.length) * 100)};
  }

  function summaryRow(label, valueText) {
    return `<div class="member-profile-summary-row"><span>${Pyrk.esc(label)}</span><strong>${Pyrk.esc(valueText || '—')}</strong></div>`;
  }

  function activityEmpty(message) {
    return `<div class="member-profile-empty"><strong>Nothing here yet</strong><p>${Pyrk.esc(message)}</p></div>`;
  }

  function applySelfEditPermission(profile) {
    state.canEditOwnProfile = Number(profile?.can_edit_own_profile ?? 1) === 1;
    const form = byId('memberWebProfileForm');
    const editButton = byId('focusProfileEdit');
    const saveState = byId('memberProfileSaveState');
    const notice = byId('memberProfilePageNotice');

    if (editButton) editButton.hidden = !state.canEditOwnProfile;
    if (form) {
      form.querySelectorAll('input, select, textarea, button').forEach(control => {
        control.disabled = !state.canEditOwnProfile;
      });
      form.classList.toggle('is-profile-edit-disabled', !state.canEditOwnProfile);
    }

    if (!state.canEditOwnProfile) {
      state.dirty = false;
      if (saveState) saveState.textContent = 'Editing disabled';
      if (notice) {
        notice.hidden = false;
        notice.className = 'member-profile-page-notice notice';
        notice.textContent = 'Profile editing has been disabled for your account by an administrator. You can still view all profile information.';
      }
    }
  }

  function renderProfile(data) {
    const profile = data.profile || {};
    state.profile = profile;
    applySelfEditPermission(profile);

    setAvatar('memberProfilePageAvatar', profile);
    setAvatar('memberWebProfilePreview', profile);
    text('memberProfilePageName', profile.full_name || 'Pyrk member');
    text('memberProfilePageEmail', profile.email || 'No email saved');
    text('memberProfilePageStatus', statusLabel(profile.status));
    text('memberProfilePagePoints', Number(profile.loyalty_points || 0));
    text('memberProfilePageWalks', Number(profile.total_walks || 0));
    text('memberProfilePageKm', Number(profile.total_kilometers || 0).toFixed(1));
    text('memberProfilePageBadges', (data.badges || []).length);

    const ready = completeness(profile);
    text('memberProfilePageCompleteness', `${ready.percent}% complete`);
    text('memberProfileReadinessPercent', `${ready.percent}%`);
    const readinessBar = byId('memberProfileReadinessBar');
    if (readinessBar) readinessBar.style.width = `${ready.percent}%`;
    text(
      'memberProfileReadinessText',
      ready.percent === 100
        ? 'Your profile is complete and ready for safer walk participation.'
        : 'Complete the missing details so Pyrk can contact and support you when needed.'
    );
    const readinessList = byId('memberProfileReadinessList');
    if (readinessList) {
      readinessList.innerHTML = ready.checks.map(([label, complete]) => `
        <div class="member-profile-readiness-item ${complete ? 'is-ready' : 'is-missing'}">
          <span>${complete ? '✓' : '!'}</span><strong>${Pyrk.esc(label)}</strong><small>${complete ? 'Complete' : 'Missing'}</small>
        </div>`).join('');
    }

    const summary = byId('memberProfileSummaryList');
    if (summary) {
      summary.innerHTML = [
        summaryRow('Member since', profile.created_at ? Pyrk.formatDate(profile.created_at) : '—'),
        summaryRow('Date of birth', profile.date_of_birth ? Pyrk.formatDate(profile.date_of_birth) : '—'),
        summaryRow('Gender', genderLabel(profile.gender)),
        summaryRow('Mobile', profile.mobile || '—'),
        summaryRow('Emergency contact', profile.emergency_contact_name || '—'),
        summaryRow('Photo consent', Number(profile.photo_consent || 0) === 1 ? 'Allowed' : 'Not allowed'),
      ].join('');
    }

    renderGroups(data.member_groups || []);
    renderBadges(data.badges || []);
    renderWaivers(data.waivers || []);
    renderPhotos(data.photos || []);
    fillForm(profile);
    updateSaveState(false);
  }

  function renderGroups(groups) {
    const box = byId('memberProfilePageGroups');
    if (!box) return;
    box.innerHTML = groups.length
      ? groups.map(group => `<span class="member-profile-chip">👥 ${Pyrk.esc(group.group_name || 'Member group')}</span>`).join('')
      : '<p class="muted small">You are not assigned to a member group yet.</p>';
  }

  function renderBadges(badges) {
    const box = byId('memberProfilePageBadgesList');
    if (!box) return;
    box.innerHTML = badges.length
      ? badges.slice(0, 6).map(badge => `
          <div class="member-profile-activity-row badge-row">
            <span class="member-profile-activity-icon">${Pyrk.esc(badge.badge_icon || '🏅')}</span>
            <div><strong>${Pyrk.esc(badge.badge_name || 'Badge')}</strong><small>${badge.earned_at ? Pyrk.formatDate(badge.earned_at) : 'Earned'}</small></div>
          </div>`).join('')
      : activityEmpty('Complete eligible walks to earn your first badge.');
  }

  function renderWaivers(waivers) {
    const box = byId('memberProfilePageWaivers');
    if (!box) return;
    box.innerHTML = waivers.length
      ? waivers.slice(0, 6).map(waiver => `
          <div class="member-profile-activity-row">
            <span class="member-profile-activity-icon">✍️</span>
            <div><strong>${Pyrk.esc(waiver.walk_title || waiver.waiver_title || 'Walk waiver')}</strong><small>${Pyrk.esc(waiver.waiver_title || 'Waiver')} · ${Pyrk.formatDateTime(waiver.signed_at)}</small></div>
          </div>`).join('')
      : activityEmpty('Signed walk waivers will appear here.');
  }

  function renderPhotos(photos) {
    const box = byId('memberProfilePagePhotos');
    if (!box) return;
    box.innerHTML = photos.length
      ? photos.slice(0, 6).map(photo => `
          <div class="member-profile-activity-row">
            <span class="member-profile-activity-icon">📷</span>
            <div><strong>${Pyrk.esc(photo.title || photo.walk_title || 'Walk photo')}</strong><small>${Pyrk.esc(photo.walk_title || '')}${photo.walk_title ? ' · ' : ''}${Pyrk.esc(statusLabel(photo.status))} · ${Number(photo.votes_count || 0)} votes</small></div>
          </div>`).join('')
      : activityEmpty('Your uploaded walk photos will appear here.');
  }

  function fillForm(profile) {
    const name = splitName(profile.full_name || '');
    value('memberWebFirstName', profile.first_name || name.first);
    value('memberWebLastName', profile.last_name || name.last);
    value('memberWebFullName', profile.full_name || '');
    value('memberWebEmail', profile.email || '');
    value('memberWebMobile', profile.mobile || '');
    value('memberWebDateOfBirth', profile.date_of_birth ? String(profile.date_of_birth).slice(0, 10) : '');
    value('memberWebGender', profile.gender || '');
    value('memberWebEmergencyName', profile.emergency_contact_name || '');
    value('memberWebEmergencyMobile', profile.emergency_contact_mobile || '');
    value('memberWebMedicalConditions', profile.medical_conditions || '');
    const consent = byId('memberWebPhotoConsent');
    if (consent) consent.checked = Number(profile.photo_consent || 0) === 1;
    const photoInput = byId('memberWebProfilePhoto');
    if (photoInput) photoInput.value = '';
  }

  function updateSaveState(dirty) {
    if (!state.canEditOwnProfile) {
      state.dirty = false;
      const disabledStatus = byId('memberProfileSaveState');
      if (disabledStatus) disabledStatus.textContent = 'Editing disabled';
      return;
    }
    state.dirty = Boolean(dirty);
    const status = byId('memberProfileSaveState');
    if (status) {
      status.textContent = state.dirty ? 'Unsaved changes' : 'Up to date';
      status.classList.toggle('is-dirty', state.dirty);
    }
    const reset = byId('resetMemberWebProfile');
    if (reset) reset.disabled = !state.dirty;
  }

  function showPageError(message) {
    const notice = byId('memberProfilePageNotice');
    if (!notice) return;
    notice.hidden = false;
    notice.className = 'member-profile-page-notice notice bad';
    notice.textContent = message || 'Could not load your profile.';
  }

  async function loadProfile() {
    const response = await Pyrk.get('members.php', {action: 'profile'});
    if (!response.ok) {
      showPageError(response.message);
      return;
    }
    const notice = byId('memberProfilePageNotice');
    if (notice) notice.hidden = true;
    renderProfile(response.data || {});
  }

  function validateForm(form) {
    const first = String(byId('memberWebFirstName')?.value || '').trim();
    const last = String(byId('memberWebLastName')?.value || '').trim();
    if (!first || !last) {
      return 'First name and last name are required.';
    }
    const email = String(byId('memberWebEmail')?.value || '').trim();
    if (!email || !/^\S+@\S+\.\S+$/.test(email)) {
      return 'Enter a valid email address.';
    }
    const dob = byId('memberWebDateOfBirth')?.value || '';
    if (dob && new Date(`${dob}T00:00:00`) > new Date()) {
      return 'Date of birth cannot be in the future.';
    }
    if (!form.checkValidity()) {
      form.reportValidity();
      return 'Please review the highlighted profile fields.';
    }
    return '';
  }

  async function saveProfile(event) {
    event.preventDefault();
    if (!state.canEditOwnProfile) {
      Pyrk.toast('memberWebProfileMessage', {ok: false, message: 'Profile editing is disabled for your account.'});
      return;
    }
    const form = event.currentTarget;
    const error = validateForm(form);
    if (error) {
      Pyrk.toast('memberWebProfileMessage', {ok: false, message: error});
      return;
    }

    const first = String(byId('memberWebFirstName')?.value || '').trim();
    const last = String(byId('memberWebLastName')?.value || '').trim();
    value('memberWebFullName', `${first} ${last}`.trim());

    const formData = new FormData(form);
    formData.append('action', 'update_profile');
    if (!byId('memberWebPhotoConsent')?.checked) formData.set('photo_consent', '0');

    const button = byId('saveMemberWebProfile');
    const original = button?.textContent || 'Save my profile';
    if (button) {
      button.disabled = true;
      button.textContent = 'Saving...';
    }
    text('memberProfileSaveState', 'Saving securely...');

    const response = await Pyrk.postForm('account.php', formData, {timeoutMs: 30000});
    Pyrk.toast('memberWebProfileMessage', response);

    if (button) {
      button.disabled = false;
      button.textContent = original;
    }

    if (response.ok) {
      if (state.previewUrl) {
        URL.revokeObjectURL(state.previewUrl);
        state.previewUrl = null;
      }
      await loadProfile();
      updateSaveState(false);
    } else {
      updateSaveState(true);
    }
  }

  function bindPage() {
    const form = byId('memberWebProfileForm');
    if (form) {
      form.addEventListener('submit', saveProfile);
      form.addEventListener('input', () => updateSaveState(true));
      form.addEventListener('change', () => updateSaveState(true));
    }

    const photo = byId('memberWebProfilePhoto');
    if (photo) {
      photo.addEventListener('change', event => {
        const file = event.target.files?.[0];
        if (!file) return;
        if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
          event.target.value = '';
          Pyrk.toast('memberWebProfileMessage', {ok: false, message: 'Choose a JPG, PNG or WebP profile photo.'});
          return;
        }
        if (state.previewUrl) URL.revokeObjectURL(state.previewUrl);
        state.previewUrl = URL.createObjectURL(file);
        setAvatar('memberWebProfilePreview', state.profile || {}, state.previewUrl);
        updateSaveState(true);
      });
    }

    byId('resetMemberWebProfile')?.addEventListener('click', () => {
      if (!state.profile) return;
      if (state.previewUrl) {
        URL.revokeObjectURL(state.previewUrl);
        state.previewUrl = null;
      }
      fillForm(state.profile);
      setAvatar('memberWebProfilePreview', state.profile);
      Pyrk.toast('memberWebProfileMessage', {ok: true, message: 'Unsaved changes were reset.'});
      updateSaveState(false);
    });

    byId('focusProfileEdit')?.addEventListener('click', () => {
      if (!state.canEditOwnProfile) return;
      byId('editProfile')?.scrollIntoView({behavior: 'smooth', block: 'start'});
      setTimeout(() => byId('memberWebFirstName')?.focus(), 350);
    });

    window.addEventListener('beforeunload', event => {
      if (!state.dirty) return;
      event.preventDefault();
      event.returnValue = '';
    });
  }

  bindPage();
  loadProfile();
})();
