let badgeState = {members: [], badges: [], groups: [], badge_group_rules_ready: false, badge_awards: [], transactions: [], selected_member: null};

function initials(name) { return String(name || 'M').trim().split(/\s+/).slice(0, 2).map(p => p[0] || '').join('').toUpperCase() || 'M'; }
function statusPill(status) { const s = String(status || 'unknown'); const cls = s === 'active' ? 'pill-green' : (s === 'inactive' ? 'pill-red' : 'pill-muted'); return `<span class="pill ${cls}">${Pyrk.esc(s.replace(/_/g, ' '))}</span>`; }
function badgeRuleLabel(b) { const type = String(b.rule_type || 'manual').replace(/_/g, ' '); return `${type}: ${Number(b.rule_value || 0)}`; }
function memberOption(m) { return `<option value="${m.id}">${Pyrk.esc(m.full_name)} · ${Number(m.loyalty_points || 0)} pts</option>`; }
function groupOption(g) { return `<option value="${g.id}">${Pyrk.esc(g.group_name)}${g.status && g.status !== 'active' ? ' · ' + Pyrk.esc(g.status) : ''}</option>`; }
function badgeAutoGroupLabel(b) {
  if (Number(b.auto_group_enabled || 0) !== 1) return '';
  const groupName = b.auto_group_name || (badgeState.groups || []).find(g => Number(g.id) === Number(b.auto_group_id))?.group_name || 'linked group';
  return `<span class="pill pill-blue">Auto group: ${Pyrk.esc(groupName)}</span>`;
}

function awardOption(a) {
  return `<option value="${a.award_id}" data-member-id="${a.user_id}">${Pyrk.esc(a.badge_icon || '🏅')} ${Pyrk.esc(a.badge_name)} · ${Pyrk.esc(a.full_name)} · ${Number(a.points_reward || 0)} pts</option>`;
}

function selectedCancelAward() {
  const awardId = Number(document.getElementById('cancelBadgeAward')?.value || 0);
  return (badgeState.badge_awards || []).find(a => Number(a.award_id) === awardId) || null;
}

function renderCancelBadgeForm() {
  const memberSelect = document.getElementById('cancelBadgeMember');
  const awardSelect = document.getElementById('cancelBadgeAward');
  const preview = document.getElementById('cancelBadgePreview');
  if (!memberSelect || !awardSelect) return;

  const memberOptions = '<option value="">All members</option>' + (badgeState.members || []).map(memberOption).join('');
  if (memberSelect.innerHTML !== memberOptions) memberSelect.innerHTML = memberOptions;

  const memberId = memberSelect.value || '';
  const awards = (badgeState.badge_awards || []).filter(a => !memberId || String(a.user_id) === String(memberId));
  awardSelect.innerHTML = '<option value="">Select awarded badge</option>' + awards.map(awardOption).join('');

  if (preview) preview.innerHTML = '<p class="muted">Select an awarded badge to preview points removal.</p>';
}

function updateCancelBadgePreview() {
  const preview = document.getElementById('cancelBadgePreview');
  const award = selectedCancelAward();
  if (!preview) return;
  if (!award) {
    preview.innerHTML = '<p class="muted">Select an awarded badge to preview points removal.</p>';
    return;
  }
  preview.innerHTML = `
    <article class="cancel-badge-card">
      <span>${Pyrk.esc(award.badge_icon || '🏅')}</span>
      <div>
        <strong>${Pyrk.esc(award.badge_name)}</strong>
        <small>${Pyrk.esc(award.full_name)} · earned ${Pyrk.formatDateTime(award.earned_at)}</small>
      </div>
      <b>-${Number(award.points_reward || 0)} pts</b>
    </article>`;
}


function resetBadgeForm() {
  const form = document.getElementById('badgeForm');
  if (!form) return;
  form.reset();
  document.getElementById('badgeId').value = '';
  document.getElementById('badgeFormTitle').textContent = 'Create badge';
  document.getElementById('badgeIcon').value = '🏅';
  if (document.getElementById('badgeAutoGroupEnabled')) document.getElementById('badgeAutoGroupEnabled').checked = false;
  if (document.getElementById('badgeAutoGroupId')) document.getElementById('badgeAutoGroupId').value = '';
  Pyrk.toast('badgeMsg', {ok:true, message:''});
  document.getElementById('badgeName')?.focus();
}

function fillSelects() {
  const memberOptions = '<option value="">Select member</option>' + (badgeState.members || []).map(memberOption).join('');
  const memberSelect = document.getElementById('badgeMember');
  if (memberSelect) memberSelect.innerHTML = memberOptions;
  const badgeSelect = document.getElementById('badgeSelect');
  if (badgeSelect) badgeSelect.innerHTML = '<option value="">Select badge</option>' + (badgeState.badges || []).map(b => `<option value="${b.id}">${Pyrk.esc(b.badge_icon || '🏅')} ${Pyrk.esc(b.badge_name)}</option>`).join('');
  const groupSelect = document.getElementById('badgeAutoGroupId');
  if (groupSelect) groupSelect.innerHTML = '<option value="">No group selected</option>' + (badgeState.groups || []).map(groupOption).join('');
}

function filteredBadges() {
  const q = (document.getElementById('badgeSearch')?.value || '').toLowerCase().trim();
  const status = document.getElementById('badgeStatusFilter')?.value || '';
  return (badgeState.badges || []).filter(b => {
    const hay = `${b.badge_name || ''} ${b.description || ''} ${b.rule_type || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!status || b.status === status);
  });
}

function renderStats() {
  const badges = badgeState.badges || [];
  document.getElementById('badgeTotal').textContent = badges.length;
  document.getElementById('badgeActive').textContent = badges.filter(b => b.status === 'active').length;
  document.getElementById('badgeManual').textContent = badges.filter(b => b.rule_type === 'manual').length;
  document.getElementById('badgeAuto').textContent = badges.filter(b => ['total_km','total_walks'].includes(b.rule_type)).length;
}

function renderBadges() {
  renderStats();
  fillSelects();
  renderCancelBadgeForm();
  const canManage = !!window.PYRK_CAN_MANAGE_LOYALTY;
  const grid = document.getElementById('badgeGrid');
  if (!grid) return;
  const rows = filteredBadges();
  grid.innerHTML = rows.map(b => {
    const autoGroupLabel = badgeAutoGroupLabel(b);
    return `<article class="badge-rule-card pro-library-card">
    <div class="badge-rule-icon">${Pyrk.esc(b.badge_icon || '🏅')}</div>
    <div class="badge-rule-body">
      <div class="inline-controls tiny-controls">${statusPill(b.status)}<span class="pill pill-muted">${Pyrk.esc(badgeRuleLabel(b))}</span><span class="pill pill-muted">+${Number(b.points_reward || 0)} pts</span></div>
      <strong>${Pyrk.esc(b.badge_name)}</strong>
      <p>${Pyrk.esc(b.description || 'No description')}</p>
      ${autoGroupLabel}
    </div>
    <div class="badge-card-actions">
      ${canManage ? `<button class="btn btn-light btn-small" type="button" onclick="editBadge(${b.id})">Edit</button>` : ''}
      ${canManage && Number(b.auto_group_enabled || 0) === 1 ? `<button class="btn btn-light btn-small" type="button" onclick="syncBadgeGroup(${b.id})">Sync group</button>` : ''}
    </div>
  </article>`;
  }).join('') || '<div class="empty-state"><strong>No badges found</strong><span>Change search/filter or create your first badge.</span></div>';
}

window.editBadge = function editBadge(id) {
  const b = (badgeState.badges || []).find(x => Number(x.id) === Number(id));
  if (!b) return;
  document.getElementById('badgeFormTitle').textContent = 'Edit badge';
  document.getElementById('badgeId').value = b.id;
  document.getElementById('badgeName').value = b.badge_name || '';
  document.getElementById('badgeIcon').value = b.badge_icon || '🏅';
  document.getElementById('badgeRuleType').value = b.rule_type || 'manual';
  document.getElementById('badgeRuleValue').value = b.rule_value || 0;
  document.getElementById('badgePointsReward').value = b.points_reward || 0;
  document.getElementById('badgeStatus').value = b.status || 'active';
  if (document.getElementById('badgeAutoGroupEnabled')) document.getElementById('badgeAutoGroupEnabled').checked = Number(b.auto_group_enabled || 0) === 1;
  if (document.getElementById('badgeAutoGroupId')) document.getElementById('badgeAutoGroupId').value = b.auto_group_id || '';
  document.getElementById('badgeDescription').value = b.description || '';
  document.getElementById('badgeMsg').textContent = '';
  document.querySelector('.rewards-side-panel')?.scrollIntoView({behavior:'smooth', block:'start'});
};


window.syncBadgeGroup = async function syncBadgeGroup(id) {
  if (!confirm('Sync all existing members who already earned this badge into its linked group?')) return;
  const res = await Pyrk.post('loyalty.php', {action:'sync_badge_group', badge_id:id});
  alert(res.message || (res.ok ? 'Synced.' : 'Could not sync.'));
  if (res.ok) await loadBadges();
};

async function loadBadges() {
  const res = await Pyrk.get('loyalty.php', {action:'overview'});
  if (!res.ok) {
    console.error('Badges overview failed', res);
    document.getElementById('badgeGrid').innerHTML = `<div class="notice bad">${Pyrk.esc(res.message || 'Could not load badges.')}</div>`;
    return;
  }
  badgeState = res.data || {members: [], badges: [], groups: [], badge_awards: [], transactions: []};
  fillSelects();
  renderBadges();
  renderCancelBadgeForm?.();
}

document.getElementById('badgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  if (document.getElementById('badgeAutoGroupEnabled')?.checked && !document.getElementById('badgeAutoGroupId')?.value) {
    Pyrk.toast('badgeMsg', {ok:false, message:'Choose the target group for this badge.'});
    return;
  }
  fd.append('action', 'save_badge');
  const res = await Pyrk.postForm('loyalty.php', fd);
  Pyrk.toast('badgeMsg', res);
  if (res.ok) { resetBadgeForm(); await 
document.getElementById('cancelBadgeMember')?.addEventListener('change', () => {
  renderCancelBadgeForm();
  updateCancelBadgePreview();
});
document.getElementById('cancelBadgeAward')?.addEventListener('change', updateCancelBadgePreview);

document.getElementById('cancelBadgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const award = selectedCancelAward();
  if (!award) {
    Pyrk.toast('cancelBadgeMsg', {ok:false, message:'Select an awarded badge first.'});
    return;
  }
  const points = Number(award.points_reward || 0);
  if (!confirm(`Cancel "${award.badge_name}" for ${award.full_name}?\n\nThis will remove the badge and deduct ${points} points.`)) return;
  const res = await Pyrk.post('loyalty.php', {action:'cancel_badge_award', award_id: award.award_id});
  Pyrk.toast('cancelBadgeMsg', res);
  if (res.ok) await loadBadges();
});


loadBadges(); }
});

document.getElementById('awardBadgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  fd.append('action', 'award_badge');
  const res = await Pyrk.postForm('loyalty.php', fd);
  Pyrk.toast('awardBadgeMsg', res);
  if (res.ok) await 
document.getElementById('cancelBadgeMember')?.addEventListener('change', () => {
  renderCancelBadgeForm();
  updateCancelBadgePreview();
});
document.getElementById('cancelBadgeAward')?.addEventListener('change', updateCancelBadgePreview);

document.getElementById('cancelBadgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const award = selectedCancelAward();
  if (!award) {
    Pyrk.toast('cancelBadgeMsg', {ok:false, message:'Select an awarded badge first.'});
    return;
  }
  const points = Number(award.points_reward || 0);
  if (!confirm(`Cancel "${award.badge_name}" for ${award.full_name}?\n\nThis will remove the badge and deduct ${points} points.`)) return;
  const res = await Pyrk.post('loyalty.php', {action:'cancel_badge_award', award_id: award.award_id});
  Pyrk.toast('cancelBadgeMsg', res);
  if (res.ok) await loadBadges();
});


loadBadges();
});

document.getElementById('evaluateAllBadges')?.addEventListener('click', async () => {
  if (!confirm('Evaluate automatic badges for all members now?')) return;
  const res = await Pyrk.post('loyalty.php', {action:'evaluate_badges'});
  alert(res.message || (res.ok ? 'Done.' : 'Failed.'));
  if (res.ok) await 
document.getElementById('cancelBadgeMember')?.addEventListener('change', () => {
  renderCancelBadgeForm();
  updateCancelBadgePreview();
});
document.getElementById('cancelBadgeAward')?.addEventListener('change', updateCancelBadgePreview);

document.getElementById('cancelBadgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const award = selectedCancelAward();
  if (!award) {
    Pyrk.toast('cancelBadgeMsg', {ok:false, message:'Select an awarded badge first.'});
    return;
  }
  const points = Number(award.points_reward || 0);
  if (!confirm(`Cancel "${award.badge_name}" for ${award.full_name}?\n\nThis will remove the badge and deduct ${points} points.`)) return;
  const res = await Pyrk.post('loyalty.php', {action:'cancel_badge_award', award_id: award.award_id});
  Pyrk.toast('cancelBadgeMsg', res);
  if (res.ok) await loadBadges();
});


loadBadges();
});

document.getElementById('newBadgeBtn')?.addEventListener('click', resetBadgeForm);
document.getElementById('resetBadgeForm')?.addEventListener('click', resetBadgeForm);
document.getElementById('badgeSearch')?.addEventListener('input', renderBadges);
document.getElementById('badgeStatusFilter')?.addEventListener('change', renderBadges);


document.getElementById('cancelBadgeMember')?.addEventListener('change', () => {
  renderCancelBadgeForm();
  updateCancelBadgePreview();
});
document.getElementById('cancelBadgeAward')?.addEventListener('change', updateCancelBadgePreview);

document.getElementById('cancelBadgeForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const award = selectedCancelAward();
  if (!award) {
    Pyrk.toast('cancelBadgeMsg', {ok:false, message:'Select an awarded badge first.'});
    return;
  }
  const points = Number(award.points_reward || 0);
  if (!confirm(`Cancel "${award.badge_name}" for ${award.full_name}?\n\nThis will remove the badge and deduct ${points} points.`)) return;
  const res = await Pyrk.post('loyalty.php', {action:'cancel_badge_award', award_id: award.award_id});
  Pyrk.toast('cancelBadgeMsg', res);
  if (res.ok) await loadBadges();
});


loadBadges();


document.getElementById('badgeAutoGroupEnabled')?.addEventListener('change', e => {
  const groupSelect = document.getElementById('badgeAutoGroupId');
  if (groupSelect) groupSelect.disabled = !e.target.checked;
});
