let tierState = {tiers: [], sponsors: [], badges: [], rewards: [], members: [], expiring: []};
const esc = v => Pyrk.esc(v ?? '');
const ids = value => Array.isArray(value) ? value.map(Number).filter(Boolean) : String(value || '').split(',').map(Number).filter(Boolean);

function fmtDate(value) {
  if (!value) return '—';
  const s = String(value).slice(0, 10);
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  return m ? `${m[3]}/${m[2]}/${m[1]}` : s;
}

function selectedMulti(select) { return Array.from(select?.selectedOptions || []).map(o => Number(o.value)).filter(Boolean); }
function tierById(id) { return (tierState.tiers || []).find(t => Number(t.id) === Number(id)) || null; }
function sponsorById(id) { return (tierState.sponsors || []).find(s => Number(s.id) === Number(id)) || null; }

function fillBadgeSelect() {
  const select = document.getElementById('tierRequiredBadges');
  if (!select) return;
  select.innerHTML = (tierState.badges || []).map(b => `<option value="${Number(b.id)}">${esc(b.badge_icon || '🏅')} ${esc(b.badge_name)}</option>`).join('');
}

function resetTierForm() {
  document.getElementById('tierForm')?.reset();
  document.getElementById('tierId').value = '';
  document.getElementById('tierFormTitle').textContent = 'Create tier';
  document.getElementById('tierColor').value = '#1c7c54';
  document.getElementById('tierValidDays').value = '365';
  document.getElementById('tierSort').value = '10';
  Array.from(document.getElementById('tierRequiredBadges')?.options || []).forEach(o => o.selected = false);
}

function resetSponsorForm() {
  document.getElementById('sponsorForm')?.reset();
  document.getElementById('sponsorId').value = '';
  document.getElementById('sponsorFormTitle').textContent = 'Create sponsor';
}

function renderStats() {
  document.getElementById('tierCount').textContent = String((tierState.tiers || []).filter(t => t.status === 'active').length);
  document.getElementById('sponsorCount').textContent = String((tierState.sponsors || []).length);
  document.getElementById('tieredMemberCount').textContent = String((tierState.members || []).filter(m => m.tier_id).length);
  document.getElementById('tierExpiringCount').textContent = String((tierState.expiring || []).length);
}

function renderTiers() {
  const box = document.getElementById('tierCards');
  if (!box) return;
  const rows = [...(tierState.tiers || [])].sort((a,b) => Number(a.sort_order || 0) - Number(b.sort_order || 0));
  box.innerHTML = rows.map(t => {
    const required = ids(t.required_badges_json ? JSON.parse(t.required_badges_json || '[]') : []);
    return `<article class="tier-card" style="--tier-color:${esc(t.color || '#1c7c54')}">
      <div class="tier-card-top"><span class="tier-icon">${esc(t.icon || '🏅')}</span><span class="pill ${t.status === 'active' ? 'pill-green' : 'pill-muted'}">${esc(t.status)}</span></div>
      <h3>${esc(t.tier_name)}</h3>
      <p>${esc(t.description || 'No description')}</p>
      <div class="tier-rule-list">
        <span>${Number(t.min_points || 0)}+ points</span>
        <span>${Number(t.required_badge_count || 0)}+ badges</span>
        <span>${Number(t.level_valid_days || 0) ? Number(t.level_valid_days) + ' days validity' : 'No expiry'}</span>
        ${required.length ? `<span>${required.length} specific badge(s)</span>` : ''}
      </div>
      <button class="btn btn-light btn-small" type="button" onclick="editTier(${Number(t.id)})">Edit</button>
    </article>`;
  }).join('') || '<div class="empty-state"><strong>No tiers yet.</strong><span>Create Bronze, Silver, Gold or your own custom levels.</span></div>';
}

function renderSponsors() {
  const box = document.getElementById('sponsorCards');
  if (!box) return;
  box.innerHTML = (tierState.sponsors || []).map(s => `<article class="sponsor-card">
    <div class="sponsor-avatar">${s.logo_path ? `<img src="../${esc(s.logo_path)}" alt="">` : '🤝'}</div>
    <div><strong>${esc(s.sponsor_name)}</strong><small>${esc([s.contact_name, s.email, s.phone].filter(Boolean).join(' · ') || 'No contact details')}</small><p>${esc(s.notes || '')}</p></div>
    <div class="inline-controls tiny-controls"><span class="pill ${s.status === 'active' ? 'pill-green' : 'pill-muted'}">${esc(s.status)}</span><button class="btn btn-light btn-small" type="button" onclick="editSponsor(${Number(s.id)})">Edit</button></div>
  </article>`).join('') || '<div class="empty-state"><strong>No sponsors yet.</strong><span>Add external sponsors for prizes.</span></div>';
}

function tierPills(tierIds) {
  const list = ids(tierIds);
  if (!list.length) return '<span class="pill pill-green">All tiers</span>';
  return list.map(id => {
    const t = tierById(id);
    return `<span class="pill pill-muted">${esc(t ? (t.icon || '') + ' ' + t.tier_name : '#' + id)}</span>`;
  }).join(' ');
}

function renderPrizeEligibility() {
  const body = document.getElementById('tierPrizeBody');
  if (!body) return;
  body.innerHTML = (tierState.rewards || []).map(r => {
    const sponsor = sponsorById(r.sponsor_id);
    return `<tr>
      <td><strong>${esc(r.reward_name)}</strong><small>${Number(r.points_cost || 0)} pts · ${esc(r.status || '')}</small></td>
      <td>${sponsor ? `<strong>${esc(sponsor.sponsor_name)}</strong>` : '<span class="muted">No sponsor</span>'}</td>
      <td>${tierPills(r.tier_ids || [])}</td>
      <td>${fmtDate(r.available_from)} → ${fmtDate(r.available_until)}</td>
      <td><button class="btn btn-light btn-small" type="button" onclick="editPrizeEligibility(${Number(r.id)})">Manage access</button></td>
    </tr>`;
  }).join('') || '<tr><td colspan="5" class="muted">No prizes found.</td></tr>';
}

function renderMembers() {
  const body = document.getElementById('memberTierBody');
  if (!body) return;
  const q = (document.getElementById('memberTierSearch')?.value || '').toLowerCase().trim();
  const rows = (tierState.members || []).filter(m => !q || `${m.full_name || ''} ${m.email || ''} ${m.tier_name || ''}`.toLowerCase().includes(q));
  body.innerHTML = rows.map(m => `<tr>
    <td><strong>${esc(m.full_name)}</strong><small>${esc(m.email || m.mobile || '')}</small></td>
    <td>${m.tier_id ? `<span class="tier-chip" style="--tier-color:${esc(m.color || '#1c7c54')}">${esc(m.icon || '🏅')} ${esc(m.tier_name)}</span>` : '<span class="pill pill-muted">No tier</span>'}</td>
    <td><strong>${Number(m.loyalty_points || 0)}</strong></td>
    <td>${Number(m.badge_count || 0)}</td>
    <td>${fmtDate(m.assigned_at)}</td>
    <td>${fmtDate(m.expires_at)}</td>
    <td><button class="btn btn-light btn-small" type="button" onclick="recalculateMember(${Number(m.id)})">Recalculate</button></td>
  </tr>`).join('') || '<tr><td colspan="7" class="muted">No members found.</td></tr>';
}

function renderAll() { renderStats(); fillBadgeSelect(); renderTiers(); renderSponsors(); renderPrizeEligibility(); renderMembers(); }

window.editTier = function(id) {
  const t = tierById(id); if (!t) return;
  document.getElementById('tierFormTitle').textContent = 'Edit tier';
  document.getElementById('tierId').value = t.id;
  document.getElementById('tierName').value = t.tier_name || '';
  document.getElementById('tierCode').value = t.tier_code || '';
  document.getElementById('tierIcon').value = t.icon || '🏅';
  document.getElementById('tierColor').value = t.color || '#1c7c54';
  document.getElementById('tierStatus').value = t.status || 'active';
  document.getElementById('tierMinPoints').value = t.min_points || 0;
  document.getElementById('tierRequiredBadgeCount').value = t.required_badge_count || 0;
  document.getElementById('tierValidDays').value = t.level_valid_days || 0;
  document.getElementById('tierSort').value = t.sort_order || 0;
  document.getElementById('tierDescription').value = t.description || '';
  const selected = ids(t.required_badges_json ? JSON.parse(t.required_badges_json || '[]') : []);
  Array.from(document.getElementById('tierRequiredBadges')?.options || []).forEach(o => o.selected = selected.includes(Number(o.value)));
  document.querySelector('.tier-form-panel')?.scrollIntoView({behavior:'smooth', block:'start'});
};

window.editSponsor = function(id) {
  const s = sponsorById(id); if (!s) return;
  document.getElementById('sponsorFormTitle').textContent = 'Edit sponsor';
  document.getElementById('sponsorId').value = s.id;
  document.getElementById('sponsorName').value = s.sponsor_name || '';
  document.getElementById('sponsorContact').value = s.contact_name || '';
  document.getElementById('sponsorEmail').value = s.email || '';
  document.getElementById('sponsorPhone').value = s.phone || '';
  document.getElementById('sponsorWebsite').value = s.website || '';
  document.getElementById('sponsorLogo').value = s.logo_path || '';
  document.getElementById('sponsorNotes').value = s.notes || '';
  document.getElementById('sponsorStatus').value = s.status || 'active';
};

window.editPrizeEligibility = async function(id) {
  const r = (tierState.rewards || []).find(x => Number(x.id) === Number(id)); if (!r) return;
  const sponsorOptions = ['0: No sponsor'].concat((tierState.sponsors || []).map(s => `${s.id}: ${s.sponsor_name}`)).join('\n');
  const sponsorValue = prompt(`Sponsor for ${r.reward_name}\n\nEnter sponsor ID:\n${sponsorOptions}`, r.sponsor_id || '');
  if (sponsorValue === null) return;
  const tiersText = prompt(`Open prize to tier IDs separated by comma.\nLeave empty for ALL tiers.\n\nAvailable tiers:\n${(tierState.tiers || []).map(t => `${t.id}: ${t.tier_name}`).join('\n')}`, (r.tier_ids || []).join(','));
  if (tiersText === null) return;
  const from = prompt('Available from date YYYY-MM-DD, empty for no start date', r.available_from || '');
  if (from === null) return;
  const until = prompt('Available until date YYYY-MM-DD, empty for no end date', r.available_until || '');
  if (until === null) return;
  const res = await Pyrk.post('loyalty_tiers.php', {action:'save_reward_eligibility', reward_id:id, sponsor_id:Number(sponsorValue || 0), tier_ids: tiersText, available_from: from, available_until: until});
  alert(res.message || (res.ok ? 'Saved.' : 'Failed.'));
  if (res.ok) await loadTierAdmin();
};

async function loadTierAdmin() {
  const res = await Pyrk.get('loyalty_tiers.php', {action:'overview'});
  if (!res.ok) { alert(res.message || 'Could not load tiers.'); return; }
  tierState = res.data || tierState;
  renderAll();
}

async function recalculateMember(id) {
  const res = await Pyrk.post('loyalty_tiers.php', {action:'recalculate_member', member_id:id});
  alert(res.message || (res.ok ? 'Done.' : 'Failed.'));
  if (res.ok) await loadTierAdmin();
}

window.recalculateMember = recalculateMember;

document.getElementById('tierForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget);
  fd.append('action','save_tier');
  const select = document.getElementById('tierRequiredBadges');
  fd.delete('required_badge_ids[]');
  selectedMulti(select).forEach(id => fd.append('required_badge_ids[]', id));
  const res = await Pyrk.postForm('loyalty_tiers.php', fd);
  Pyrk.toast('tierMsg', res);
  if (res.ok) { resetTierForm(); await loadTierAdmin(); }
});

document.getElementById('sponsorForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget); fd.append('action','save_sponsor');
  const res = await Pyrk.postForm('loyalty_tiers.php', fd);
  Pyrk.toast('sponsorMsg', res);
  if (res.ok) { resetSponsorForm(); await loadTierAdmin(); }
});

document.getElementById('newTierBtn')?.addEventListener('click', resetTierForm);
document.getElementById('resetTierForm')?.addEventListener('click', resetTierForm);
document.getElementById('newSponsorBtn')?.addEventListener('click', resetSponsorForm);
document.getElementById('resetSponsorForm')?.addEventListener('click', resetSponsorForm);
document.getElementById('memberTierSearch')?.addEventListener('input', renderMembers);
document.getElementById('recalcAllTiersBtn')?.addEventListener('click', async () => {
  if (!confirm('Recalculate tiers for all active members now?')) return;
  const res = await Pyrk.post('loyalty_tiers.php', {action:'recalculate_all'});
  alert(res.message || (res.ok ? 'Done.' : 'Failed.'));
  if (res.ok) await loadTierAdmin();
});
document.getElementById('expireTiersBtn')?.addEventListener('click', async () => {
  const res = await Pyrk.post('loyalty_tiers.php', {action:'expire_now'});
  alert(res.message || (res.ok ? 'Done.' : 'Failed.'));
  if (res.ok) await loadTierAdmin();
});

loadTierAdmin();
