function niceKey(key) {
  return String(key).replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}

function statLabel(key) {
  return ({
    members: 'Members',
    active_routes: 'Active routes',
    upcoming_walks: 'Active walks',
    registrations: 'Active registrations',
    finished_attendance: 'Finished attendance',
    club_kilometers: 'Club kilometers',
    pending_photos: 'Pending photos',
    votes: 'Photo votes',
    today_checkins: 'Today check-ins'
  }[key] || niceKey(key));
}

function statIcon(key) {
  return ({members:'👥', active_routes:'🗺️', upcoming_walks:'🥾', registrations:'✅', finished_attendance:'🏁', club_kilometers:'📍', pending_photos:'📸', votes:'🗳️', today_checkins:'▣'}[key] || '•');
}

function statHref(key) {
  return ({
    members: 'members.php',
    active_routes: 'routes.php',
    upcoming_walks: 'walks.php',
    registrations: 'walks.php',
    finished_attendance: 'attendance.php',
    club_kilometers: 'members.php',
    pending_photos: 'photos.php',
    votes: 'photos.php',
    today_checkins: 'attendance.php'
  }[key] || '#');
}

function asset(path) {
  return path ? '../' + String(path).replace(/^\/+/, '') : '';
}

function avatarPerson(name, photo) {
  if (photo) return `<img class="avatar-img" src="${Pyrk.esc(asset(photo))}" alt="${Pyrk.esc(name || 'Member')}">`;
  return `<div class="avatar">${Pyrk.esc(String(name || '?').slice(0,1).toUpperCase())}</div>`;
}

function setDashboardMessage(message, ok = false) {
  const el = document.getElementById('dashboardLoadMsg');
  if (!el) return;
  el.innerHTML = message ? `<p class="notice ${ok ? 'ok' : 'bad'}">${Pyrk.esc(message)}</p>` : '';
}

function safeSet(id, html) {
  const el = document.getElementById(id);
  if (el) el.innerHTML = html;
}

function integer(value) {
  const number = Number(value || 0);
  return Number.isFinite(number) ? Math.max(0, Math.round(number)) : 0;
}

function displayWalkDate(value) {
  if (!value) return 'Date not set';
  if (typeof Pyrk.formatDate === 'function') return Pyrk.formatDate(value);
  const raw = String(value).slice(0, 10);
  const parts = raw.split('-');
  return parts.length === 3 ? `${parts[2]}/${parts[1]}/${parts[0]}` : raw;
}

function displayWalkTime(value) {
  return value ? String(value).slice(0, 5) : '—';
}

function dateChipParts(value) {
  const raw = String(value || '').slice(0, 10);
  const parts = raw.split('-');
  if (parts.length !== 3) return {day: '—', month: ''};
  const date = new Date(`${raw}T12:00:00`);
  const month = Number.isNaN(date.getTime()) ? parts[1] : date.toLocaleString(undefined, {month: 'short'});
  return {day: parts[2], month};
}

function statusLabel(value) {
  const status = String(value || '').toLowerCase();
  return ({open:'Open', closed:'Closed', draft:'Draft'}[status] || niceKey(status || 'active'));
}

function renderActiveWalkSummary(summary = {}) {
  const cards = [
    ['🥾', 'Active walks', integer(summary.walks), 'Current and upcoming'],
    ['✅', 'Registrations', integer(summary.registrations), 'Active walks only'],
    ['👥', 'Total capacity', integer(summary.capacity), 'Across active walks'],
    ['＋', 'Places available', integer(summary.available_places), 'Remaining capacity']
  ];

  safeSet('activeWalkSummary', cards.map(([icon, label, value, note]) => `
    <div class="active-summary-card">
      <span class="active-summary-icon">${icon}</span>
      <div><small>${Pyrk.esc(label)}</small><strong>${value}</strong><em>${Pyrk.esc(note)}</em></div>
    </div>`).join(''));
}

function renderActiveWalks(walks = []) {
  if (!Array.isArray(walks) || walks.length === 0) {
    safeSet('upcomingWalks', `
      <div class="active-walk-empty">
        <span>🥾</span>
        <strong>No active walks</strong>
        <p>There are no current or upcoming walks to report.</p>
        <a class="btn btn-small" href="walks.php">Schedule a walk</a>
      </div>`);
    return;
  }

  safeSet('upcomingWalks', walks.map(w => {
    const registered = integer(w.registered_count);
    const capacity = integer(w.capacity);
    const available = capacity > 0 ? integer(w.available_places) : 0;
    const checkedIn = integer(w.checked_in_count);
    const finished = integer(w.finished_count);
    const waivers = integer(w.waiver_signed_count);
    const waitlisted = integer(w.waitlisted_count);
    const percent = capacity > 0 ? Math.min(100, Math.max(0, Number(w.occupancy_percent || ((registered / capacity) * 100)))) : 0;
    const date = dateChipParts(w.walk_date);
    const status = String(w.status || '').toLowerCase();
    const capacityText = capacity > 0 ? `${registered} of ${capacity}` : `${registered}`;
    const placeText = capacity > 0 ? available : 'Unlimited';
    const waiverText = Number(w.waiver_required || 0) === 1 ? waivers : 'Not required';

    return `
      <article class="active-walk-registration-card">
        <div class="active-walk-card-head">
          <div class="active-walk-date-chip"><strong>${Pyrk.esc(date.day)}</strong><span>${Pyrk.esc(date.month)}</span></div>
          <div class="active-walk-card-title">
            <div class="active-walk-pills">
              <span class="active-status-pill status-${Pyrk.esc(status || 'active')}">${Pyrk.esc(statusLabel(status))}</span>
              <span class="active-access-pill">${String(w.access_type || '') === 'invitation_only' ? 'Invitation only' : 'Open registration'}</span>
            </div>
            <h3>${Pyrk.esc(w.title || 'Untitled walk')}</h3>
            <p>${Pyrk.esc(w.route_name || 'Route not set')} · ${Number(w.total_km || 0).toFixed(1)} KM · ${displayWalkDate(w.walk_date)} · ${displayWalkTime(w.start_time)}</p>
          </div>
          <div class="active-walk-registration-total">
            <strong>${capacityText}</strong>
            <span>registered</span>
          </div>
        </div>

        <div class="active-registration-progress" aria-label="${registered} registrations out of ${capacity || 'unlimited'} capacity">
          <span style="width:${percent.toFixed(1)}%"></span>
        </div>

        <div class="active-walk-metrics">
          <div><small>Registered</small><strong>${registered}</strong></div>
          <div><small>Available</small><strong>${placeText}</strong></div>
          <div><small>Waivers signed</small><strong>${waiverText}</strong></div>
          <div><small>Checked in</small><strong>${checkedIn}</strong></div>
          <div><small>Finished</small><strong>${finished}</strong></div>
          <div><small>Waitlisted</small><strong>${waitlisted}</strong></div>
        </div>

        <div class="active-walk-card-actions">
          <a class="btn btn-light btn-small" href="walks.php">Manage registrations</a>
          <a class="btn btn-small" href="attendance.php?walk_id=${integer(w.id)}">Open attendance</a>
        </div>
      </article>`;
  }).join(''));
}

function renderDashboardFallback(message = '') {
  const ordered = ['members','active_routes','upcoming_walks','registrations','club_kilometers','pending_photos','today_checkins','votes'];
  safeSet('reportStats', ordered.map(k => `<a class="stat stat-pro clickable-stat" href="${statHref(k)}"><span>${statIcon(k)} ${statLabel(k)}</span><strong>0</strong><em>Open</em></a>`).join(''));
  renderActiveWalkSummary({});
  renderActiveWalks([]);
  safeSet('topWalkers', '<tr><td colspan="4">No walker data loaded.</td></tr>');
  safeSet('pendingPhotos', '<p class="muted">No pending photo data loaded.</p>');
  safeSet('recentMembers', '<p class="muted">No recent member data loaded.</p>');
  if (message) setDashboardMessage(message, false);
}

async function loadAdminDashboard() {
  try {
    const res = await Pyrk.get('reports.php');

    if (!res || !res.ok) {
      const msg = res?.message || 'Could not load dashboard data. Please refresh or login again.';
      renderDashboardFallback(msg);
      return;
    }

    setDashboardMessage('', true);
    const s = res.data?.stats || {};
    const ordered = ['members','active_routes','upcoming_walks','registrations','club_kilometers','pending_photos','today_checkins','votes'];
    safeSet('reportStats', ordered.map(k => `<a class="stat stat-pro clickable-stat" href="${statHref(k)}"><span>${statIcon(k)} ${statLabel(k)}</span><strong>${k === 'club_kilometers' ? Number(s[k] || 0).toFixed(1) : (s[k] ?? 0)}</strong><em>Open</em></a>`).join(''));

    renderActiveWalkSummary(res.data?.active_walk_summary || {});
    renderActiveWalks(res.data?.active_walks || res.data?.upcoming_walks || []);

    safeSet('topWalkers', (res.data?.top_walkers || []).map((w, i)=>`<tr class="clickable-row" onclick="window.location.href='members.php?open=${w.user_id}'"><td><div class="identity-cell">${avatarPerson(w.full_name, w.profile_photo_path)}<div><strong>#${i+1} ${Pyrk.esc(w.full_name)}</strong><small>Top community walker</small></div></div></td><td>${w.total_walks || 0}</td><td>${Number(w.total_kilometers || 0).toFixed(1)}</td><td>${w.loyalty_points || 0}</td></tr>`).join('') || '<tr><td colspan="4">No walkers yet.</td></tr>');

    safeSet('pendingPhotos', (res.data?.pending_photos || []).map(p => `<a href="photos.php" class="mini-list-link"><strong>${Pyrk.esc(p.title)}</strong><span>${Pyrk.esc(p.full_name)} · ${Pyrk.esc(p.walk_title)}</span></a>`).join('') || '<p class="muted">No pending photos.</p>');

    safeSet('recentMembers', (res.data?.recent_members || []).map(m => `<a href="members.php?open=${m.id}">${avatarPerson(m.full_name, m.profile_photo_path)}<div><strong>${Pyrk.esc(m.full_name)}</strong><span>${Pyrk.esc(m.email)} · ${Pyrk.esc(m.mobile || 'No mobile')}</span></div><small>${Number(m.total_kilometers || 0).toFixed(1)} KM</small></a>`).join('') || '<p class="muted">No members yet.</p>');
  } catch (error) {
    console.error('Dashboard load failed', error);
    renderDashboardFallback(error?.message || 'Dashboard data could not load.');
  }
}

loadAdminDashboard();
