let groupState = {groups: [], members: [], selectedGroup: null, selectedMembers: []};

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 pill(status) { return `<span class="pill ${status === 'active' ? 'pill-green' : 'pill-muted'}">${Pyrk.esc(status || 'active')}</span>`; }
function canManage() { return !!window.PYRK_CAN_MANAGE_GROUPS; }

function signupCodePill(group) {
  const code = String(group.signup_code || '').trim();
  const enabled = Number(group.signup_code_enabled || 0) === 1;
  if (!code) return '<span class="pill pill-muted">No signup code</span>';
  return `<span class="pill ${enabled ? 'pill-green' : 'pill-muted'}">${enabled ? 'Code active' : 'Code stopped'} · ${Pyrk.esc(code)}</span>`;
}

function cleanSignupCode(value) {
  return String(value || '').toUpperCase().replace(/[^A-Z0-9_-]+/g, '').slice(0, 64);
}

function generateSignupCodeFromName() {
  const base = cleanSignupCode((document.getElementById('groupName')?.value || 'GROUP').replace(/\s+/g, '')).slice(0, 10) || 'GROUP';
  const suffix = Math.random().toString(36).slice(2, 8).toUpperCase().replace(/[^A-Z0-9]/g, '');
  return `${base}-${suffix}`;
}

function syncSignupCodeState() {
  const input = document.getElementById('signupCode');
  const toggle = document.getElementById('signupCodeEnabled');
  if (!input || !toggle) return;
  input.value = cleanSignupCode(input.value);
  input.placeholder = toggle.checked ? 'Required when active' : 'Optional, kept for later';
}


function renderStats() {
  document.getElementById('groupTotal').textContent = groupState.groups.length;
  document.getElementById('groupActive').textContent = groupState.groups.filter(g => g.status === 'active').length;
  document.getElementById('groupedMembers').textContent = groupState.groups.reduce((sum,g)=>sum+Number(g.member_count||0),0);
  document.getElementById('availableMembers').textContent = groupState.members.length;
}
function filteredGroups() {
  const q = (document.getElementById('groupSearch')?.value || '').toLowerCase().trim();
  const status = document.getElementById('groupStatusFilter')?.value || '';
  return groupState.groups.filter(g => {
    const hay = `${g.group_name || ''} ${g.description || ''} ${g.signup_code || ''}`.toLowerCase();
    return (!q || hay.includes(q)) && (!status || g.status === status);
  });
}
function renderGroups() {
  const rows = filteredGroups();
  document.getElementById('groupsGrid').innerHTML = rows.map(g => `<article class="group-card enterprise-card">
    <div class="group-card-icon">👥</div>
    <div class="group-card-body"><div class="inline-controls tiny-controls">${pill(g.status)}<span class="pill pill-muted">${Number(g.member_count || 0)} members</span>${signupCodePill(g)}</div><h3>${Pyrk.esc(g.group_name)}</h3><p>${Pyrk.esc(g.description || 'No description')}</p><small>Created ${Pyrk.esc(String(g.created_at || '').slice(0,10) || '—')}</small></div>
    <div class="group-card-actions">
      ${canManage() ? `<button class="btn btn-light btn-small" type="button" onclick="editGroup(${g.id})">Edit</button><button class="btn btn-small" type="button" onclick="openGroupMembers(${g.id})">Members</button>` : `<button class="btn btn-light btn-small" type="button" onclick="openGroupMembers(${g.id})">View members</button>`}
    </div>
  </article>`).join('') || '<p class="muted">No groups found.</p>';
}
function resetGroupForm() {
  document.getElementById('groupForm')?.reset();
  document.getElementById('groupId').value = '';
  document.getElementById('groupFormTitle').textContent = 'Create group';
  document.getElementById('groupMsg').textContent = '';
  if (document.getElementById('signupCode')) document.getElementById('signupCode').value = '';
  if (document.getElementById('signupCodeEnabled')) document.getElementById('signupCodeEnabled').checked = false;
  syncSignupCodeState();
}
window.editGroup = function editGroup(id) {
  const g = groupState.groups.find(x => Number(x.id) === Number(id));
  if (!g) return;
  document.getElementById('groupFormTitle').textContent = 'Edit group';
  document.getElementById('groupId').value = g.id;
  document.getElementById('groupName').value = g.group_name || '';
  document.getElementById('groupStatus').value = g.status || 'active';
  document.getElementById('groupDescription').value = g.description || '';
  if (document.getElementById('signupCode')) document.getElementById('signupCode').value = g.signup_code || '';
  if (document.getElementById('signupCodeEnabled')) document.getElementById('signupCodeEnabled').checked = Number(g.signup_code_enabled || 0) === 1;
  syncSignupCodeState();
  Pyrk.openModal('groupFormModal');
};
function renderGroupMemberChecks() {
  const q = (document.getElementById('groupMemberSearch')?.value || '').toLowerCase().trim();
  const selected = new Set((groupState.selectedMembers || []).map(m => Number(m.id)));
  const rows = (groupState.members || []).filter(m => !q || `${m.full_name || ''} ${m.email || ''} ${m.mobile || ''}`.toLowerCase().includes(q));
  document.getElementById('groupMembersList').innerHTML = rows.map(m => `<label class="enterprise-checkbox-row"><input class="group-member-check" type="checkbox" value="${m.id}" ${selected.has(Number(m.id)) ? 'checked' : ''}><div class="identity-cell">${avatarHtml(m)}<div><strong>${Pyrk.esc(m.full_name)}</strong><small>${Pyrk.esc(m.mobile || m.email || '')} · ${Number(m.total_kilometers || 0).toFixed(1)} KM · ${Number(m.loyalty_points || 0)} pts</small></div></div></label>`).join('') || '<p class="muted">No members found.</p>';
}
window.openGroupMembers = async function openGroupMembers(id) {
  Pyrk.openModal('groupMembersModal');
  document.getElementById('membersGroupId').value = id;
  document.getElementById('groupMembersTitle').textContent = 'Manage group members';
  document.getElementById('groupMembersSub').textContent = 'Loading...';
  document.getElementById('groupMembersList').innerHTML = '<p class="muted">Loading group members...</p>';
  const res = await Pyrk.get('groups.php', {action:'detail', id});
  if (!res.ok) { document.getElementById('groupMembersList').innerHTML = `<div class="notice bad">${Pyrk.esc(res.message)}</div>`; return; }
  groupState.selectedGroup = res.data.group;
  groupState.selectedMembers = res.data.members || [];
  document.getElementById('groupMembersTitle').textContent = res.data.group.group_name || 'Manage group members';
  document.getElementById('groupMembersSub').textContent = `${Number(res.data.group.member_count || 0)} current members`;
  renderGroupMemberChecks();
};
async function loadGroups() {
  const res = await Pyrk.get('groups.php', {action:'list'});
  if (!res.ok) { document.getElementById('groupsGrid').innerHTML = `<p class="bad">${Pyrk.esc(res.message)}</p>`; return; }
  groupState = {...groupState, ...res.data};
  renderStats(); renderGroups();
}


document.getElementById('signupCode')?.addEventListener('input', syncSignupCodeState);
document.getElementById('signupCodeEnabled')?.addEventListener('change', syncSignupCodeState);
document.getElementById('generateSignupCodeBtn')?.addEventListener('click', () => {
  const input = document.getElementById('signupCode');
  if (input) input.value = generateSignupCodeFromName();
  const toggle = document.getElementById('signupCodeEnabled');
  if (toggle) toggle.checked = true;
  syncSignupCodeState();
});
document.getElementById('copySignupCodeBtn')?.addEventListener('click', async () => {
  const code = cleanSignupCode(document.getElementById('signupCode')?.value || '');
  if (!code) { alert('No code to copy.'); return; }
  try {
    await navigator.clipboard.writeText(code);
    alert('Signup code copied.');
  } catch {
    prompt('Copy signup code:', code);
  }
});

document.getElementById('openGroupModal')?.addEventListener('click', () => { resetGroupForm(); Pyrk.openModal('groupFormModal'); });
document.getElementById('groupSearch')?.addEventListener('input', renderGroups);
document.getElementById('groupStatusFilter')?.addEventListener('change', renderGroups);
document.getElementById('groupMemberSearch')?.addEventListener('input', e => { e.preventDefault(); renderGroupMemberChecks(); });
document.getElementById('groupForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const fd = new FormData(e.currentTarget); fd.append('action', 'save_group');
  const res = await Pyrk.postForm('groups.php', fd);
  Pyrk.toast('groupMsg', res);
  if (res.ok) { await loadGroups(); setTimeout(()=>Pyrk.closeModal('groupFormModal'), 450); }
});
document.getElementById('groupMembersForm')?.addEventListener('submit', async e => {
  e.preventDefault();
  const selected = Array.from(document.querySelectorAll('.group-member-check:checked')).map(x => Number(x.value));
  const res = await Pyrk.post('groups.php', {action:'sync_members', group_id: Number(document.getElementById('membersGroupId').value), member_ids: selected});
  Pyrk.toast('groupMembersMsg', res);
  if (res.ok) { await loadGroups(); setTimeout(()=>Pyrk.closeModal('groupMembersModal'), 450); }
});

loadGroups();
