let loyaltyState = {members: [], badges: [], transactions: [], selected_member: null, settings: {points_per_km: 10, walk_completion_bonus: 25, photo_winner_points: 200}};

function publicAsset(path) { if (!path) return ''; if (/^https?:\/\//.test(path)) return path; return (window.PYRK_PUBLIC_BASE || '../') + String(path).replace(/^\/+/, ''); }
function initials(name) { return String(name || 'M').trim().split(/\s+/).slice(0, 2).map(p => p[0] || '').join('').toUpperCase() || 'M'; }
function avatarHtml(person) { return person && person.profile_photo_path ? `<img class="avatar-img" src="${Pyrk.esc(publicAsset(person.profile_photo_path))}" alt="${Pyrk.esc(person.full_name || 'Member')}">` : `<div class="avatar">${Pyrk.esc(initials(person && person.full_name))}</div>`; }
function formatDate(value) { return Pyrk.formatDateTime(value); }
function statusPill(status) { const s = String(status || 'unknown'); const cls = ['active','manual_reward','badge_earned','walk_completed','photo_winner','reward_refund'].includes(s) ? 'pill-green' : (['inactive','adjustment','reward_claim','rejected','cancelled'].includes(s) ? 'pill-red' : 'pill-muted'); return `<span class="pill ${cls}">${Pyrk.esc(s.replace(/_/g, ' '))}</span>`; }
function selectedMemberId() { return Number(document.getElementById('pointsMember')?.value || window.PYRK_SELECTED_MEMBER_ID || 0); }
function memberOption(m) { return `<option value="${m.id}">${Pyrk.esc(m.full_name)} · ${Number(m.loyalty_points || 0)} pts</option>`; }

function renderLoyaltySettings() {
  const settings = loyaltyState.settings || {};
  const pointsPerKm = Number(settings.points_per_km ?? 10);
  const bonus = Number(settings.walk_completion_bonus ?? 25);
  const winner = Number(settings.photo_winner_points ?? 200);

  const pointsInput = document.getElementById('pointsPerKmInput');
  const bonusInput = document.getElementById('walkCompletionBonusInput');
  const winnerInput = document.getElementById('photoWinnerPointsInput');
  if (pointsInput && document.activeElement !== pointsInput) pointsInput.value = pointsPerKm;
  if (bonusInput && document.activeElement !== bonusInput) bonusInput.value = bonus;
  if (winnerInput && document.activeElement !== winnerInput) winnerInput.value = winner;

  const preview = document.getElementById('loyaltyFormulaPreview');
  if (preview) {
    const exampleKm = 5;
    const examplePoints = Math.round(exampleKm * pointsPerKm) + bonus;
    preview.innerHTML = `<strong>Formula:</strong> KM × ${pointsPerKm} + ${bonus} completion bonus<br><small>Example: ${exampleKm} KM walk = ${examplePoints} points. Photo winner = ${winner} points.</small>`;
  }
}

function fillMemberSelects() {
  const members = loyaltyState.members || [];
  const options = '<option value="">All members</option>' + members.map(memberOption).join('');
  const filter = document.getElementById('transactionMemberFilter');
  if (filter) filter.innerHTML = options;
  const points = document.getElementById('pointsMember');
  if (points) {
    points.innerHTML = '<option value="">Select member</option>' + members.map(memberOption).join('');
    if (window.PYRK_SELECTED_MEMBER_ID) points.value = String(window.PYRK_SELECTED_MEMBER_ID);
  }
}
function renderStats() {
  const members = loyaltyState.members || [];
  const badges = loyaltyState.badges || [];
  const tx = loyaltyState.transactions || [];
  document.getElementById('loyaltyMemberCount').textContent = members.length;
  document.getElementById('loyaltyPointTotal').textContent = members.reduce((sum,m)=>sum+Number(m.loyalty_points||0),0);
  document.getElementById('activeBadgeCount').textContent = badges.filter(b => b.status === 'active').length;
  document.getElementById('transactionCount').textContent = tx.length;
}
function renderSelectedMember() {
  const id = selectedMemberId();
  const m = (loyaltyState.members || []).find(x => Number(x.id) === id) || loyaltyState.selected_member;
  const box = document.getElementById('selectedMemberCard'); if (!box) return;
  if (!m) { box.innerHTML = '<p class="muted">Select a member to manage loyalty points.</p>'; return; }
  box.innerHTML = `<article class="loyalty-focus-card">${avatarHtml(m)}<div><strong>${Pyrk.esc(m.full_name)}</strong><span>${Pyrk.esc(m.email || '')} · ${Pyrk.esc(m.mobile || 'No mobile')}</span></div><div class="loyalty-focus-metrics"><b>${Number(m.loyalty_points || 0)}</b><small>points</small></div><div class="loyalty-focus-metrics"><b>${Number(m.total_kilometers || 0).toFixed(1)}</b><small>km</small></div><a class="btn btn-light btn-small" href="members.php?open=${m.id}">Open profile</a></article>`;
}
function filteredTransactions() {
  const q = (document.getElementById('loyaltySearch')?.value || '').toLowerCase().trim();
  const memberId = document.getElementById('transactionMemberFilter')?.value || '';
  return (loyaltyState.transactions || []).filter(t => { const hay = `${t.full_name || ''} ${t.transaction_type || ''} ${t.description || ''} ${t.walk_title || ''}`.toLowerCase(); return (!q || hay.includes(q)) && (!memberId || String(t.user_id) === String(memberId)); });
}
function renderTransactions() {
  const rows = filteredTransactions();
  document.getElementById('transactionsBody').innerHTML = rows.map(t => `<tr><td>${formatDate(t.created_at)}</td><td><a class="identity-cell" href="members.php?open=${t.user_id}"><div class="avatar mini-avatar">${Pyrk.esc(initials(t.full_name))}</div><div><strong>${Pyrk.esc(t.full_name)}</strong><small>ID #${t.user_id}</small></div></a></td><td>${statusPill(t.transaction_type)}</td><td>${Pyrk.esc(t.description || '—')}</td><td>${Pyrk.esc(t.walk_title || '—')}</td><td><strong class="${Number(t.points || 0) < 0 ? 'bad' : 'ok'}">${Number(t.points || 0) > 0 ? '+' : ''}${Number(t.points || 0)}</strong></td></tr>`).join('') || '<tr><td colspan="6" class="muted">No loyalty transactions found.</td></tr>';
}
async function loadLoyalty() {
  const memberId = window.PYRK_SELECTED_MEMBER_ID || 0;
  const res = await Pyrk.get('loyalty.php', {action:'overview', member_id: memberId});
  if (!res.ok) { document.getElementById('transactionsBody').innerHTML = `<tr><td colspan="6" class="bad">${Pyrk.esc(res.message)}</td></tr>`; return; }
  loyaltyState = res.data || {members: [], badges: [], transactions: []};
  fillMemberSelects(); renderStats(); renderSelectedMember(); renderTransactions();
}

document.getElementById('pointsMember')?.addEventListener('change', () => { renderSelectedMember(); });
document.getElementById('loyaltySearch')?.addEventListener('input', renderTransactions);
document.getElementById('transactionMemberFilter')?.addEventListener('change', renderTransactions);
document.getElementById('loyaltySettingsForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  fd.append('action', 'save_settings');
  const res = await Pyrk.postForm('loyalty.php', fd);
  Pyrk.toast('loyaltySettingsMsg', res);
  if (res.ok && res.data.settings) {
    loyaltyState.settings = res.data.settings;
    renderLoyaltySettings();
  }
});
['pointsPerKmInput','walkCompletionBonusInput','photoWinnerPointsInput'].forEach(id => document.getElementById(id)?.addEventListener('input', () => {
  loyaltyState.settings = {
    ...(loyaltyState.settings || {}),
    points_per_km: Number(document.getElementById('pointsPerKmInput')?.value || 0),
    walk_completion_bonus: Number(document.getElementById('walkCompletionBonusInput')?.value || 0),
    photo_winner_points: Number(document.getElementById('photoWinnerPointsInput')?.value || 0)
  };
  renderLoyaltySettings();
}));


async function repairCompletedWalkPoints(){
  const btn = document.getElementById('repairWalkPointsBtn');
  const msg = document.getElementById('repairWalkPointsMsg');
  if (!btn) return;
  const settings = loyaltyState.settings || {};
  const pointsPerKm = Number(settings.points_per_km ?? 10);
  const bonus = Number(settings.walk_completion_bonus ?? 25);
  const ok = confirm(`Recalculate completed-walk points using the current rules?\n\nFormula: KM × ${pointsPerKm} + ${bonus} bonus\n\nManual adjustments and badge rewards will not be changed.`);
  if (!ok) return;
  btn.disabled = true;
  if (msg) { msg.className = 'notice'; msg.textContent = 'Repairing completed-walk points...'; }
  const fd = new FormData();
  fd.append('action', 'repair_walk_completion_points');
  const res = await Pyrk.postForm('loyalty.php', fd);
  if (msg) {
    msg.className = 'notice ' + (res.ok ? 'ok' : 'bad');
    const data = res.data || {};
    msg.innerHTML = res.ok
      ? `${Pyrk.esc(res.message || 'Repair complete.')}<br><small>Checked: ${Number(data.checked || 0)} · Fixed: ${Number(data.fixed || 0)} · Members updated: ${Number(data.members_touched || 0)} · Point delta: ${Number(data.points_delta || 0)}</small>`
      : Pyrk.esc(res.message || 'Could not repair points.');
  }
  btn.disabled = false;
  if (res.ok) await loadLoyalty();
}

document.getElementById('pointsForm')?.addEventListener('submit', async e => { e.preventDefault(); const fd = new FormData(e.currentTarget); fd.append('action', 'adjust_points'); const res = await Pyrk.postForm('loyalty.php', fd); Pyrk.toast('pointsMsg', res); if (res.ok) { e.currentTarget.reset(); await loadLoyalty(); } });
document.getElementById('repairWalkPointsBtn')?.addEventListener('click', repairCompletedWalkPoints);

loadLoyalty();
