const { fmt, ui, $ } = Admin;

const featureCatalogue = [
  'home', 'movies', 'shows', 'favorites', 'search', 'recent_searches',
  'genre_browse', 'for_you', 'for_you_time', 'recommendation', 'continue',
  'latest', 'my_shows', 'details', 'playback', 'notifications', 'profiles', 'settings',
];

const label = (value) => {
  const text = String(value || '—').replaceAll('_', ' ');
  if (text === 'favorites') return 'Favourites';
  if (text === 'abandoned') return 'Abandoned / interrupted';
  return text;
};

function renderEvents(events) {
  const grouped = new Map();
  events.forEach((event) => {
    if (!grouped.has(event.journeyId)) grouped.set(event.journeyId, []);
    grouped.get(event.journeyId).push(event);
  });
  let journeyNumber = grouped.size;
  const rows = [];
  grouped.forEach((steps) => {
    steps.sort((a, b) => a.sequence - b.sequence);
    const number = journeyNumber--;
    steps.forEach((event) => {
      const path = event.source && event.target ? label(event.source) + ' → ' + label(event.target)
        : label(event.target || event.screen);
      const content = event.itemId ? label(event.itemType) + ' · ' + event.itemId : '—';
      rows.push('<tr><td class="muted">' + fmt.when(event.occurredAt) + '</td>' +
        '<td class="num">' + number + '</td><td>' + fmt.escape(label(event.action)) + '</td>' +
        '<td>' + fmt.escape(path) + '</td><td>' + fmt.escape(label(event.feature)) + '</td>' +
        '<td class="muted">' + fmt.escape(content) + '</td><td>' + fmt.escape(label(event.outcome)) + '</td></tr>');
    });
  });
  $('journeys-events').innerHTML = rows.length ? rows.join('') : ui.emptyRow(7, 'No journey events in this window.');
}

Admin.onRefresh(async () => {
  const selected = $('journeys-user').value;
  const payload = await Admin.api('/admin/api/journeys?days=' + $('journeys-days').value +
    (selected ? '&userId=' + encodeURIComponent(selected) : ''));
  const users = payload.users || [];
  const existing = $('journeys-user').value;
  $('journeys-user').innerHTML = '<option value="">All users</option>' + users.map((user) =>
    '<option value="' + fmt.escape(user.userId) + '">' + fmt.escape(user.username || user.userId) + '</option>').join('');
  if (users.some((user) => user.userId === existing)) $('journeys-user').value = existing;

  const stats = payload.stats || {};
  $('journeys-tiles').innerHTML = ui.tiles([
    ['journeys', fmt.number(stats.journeys || 0), { icon: 'list', tone: 'data' }],
    ['viewers', fmt.number(stats.viewers || 0), { icon: 'people', tone: 'info' }],
    ['completion', Math.round((stats.completionRate || 0) * 100) + '%', { icon: 'check', tone: 'ok' }],
    ['abandoned', fmt.number(stats.abandoned || 0), { icon: 'alert', tone: 'note' }],
    ['active now', fmt.number(stats.active || 0), { icon: 'pulse', tone: 'info' }],
    ['average steps', Number(stats.averageSteps || 0).toFixed(1), { icon: 'chart' }],
    ['average visit', fmt.duration(stats.averageTimeMs || 0), { icon: 'clock', small: true }],
    ['history kept', payload.retentionDays + ' days', { icon: 'clock', small: true }],
  ]);

  const used = new Map((payload.features || []).map((feature) => [feature.feature, feature]));
  const features = [...new Set([...featureCatalogue, ...used.keys()])];
  $('journeys-features').innerHTML = features.map((name) => {
    const stat = used.get(name);
    const uses = stat?.uses || 0;
    const status = uses === 0 ? ui.tag('not used', 'warn') : uses < 3 ? ui.tag('rare', 'note') : ui.tag('used', 'ok');
    return '<tr><td>' + fmt.escape(label(name)) + '</td><td class="num">' + fmt.number(uses) +
      '</td><td class="muted">' + (stat ? fmt.when(stat.lastUsedAt) : '—') + '</td><td>' + status + '</td></tr>';
  }).join('');

  const actions = payload.actions || [];
  $('journeys-actions').innerHTML = actions.length ? actions.map((action) =>
    '<tr><td>' + fmt.escape(label(action.category)) + '</td><td>' + fmt.escape(label(action.action)) +
    '</td><td class="num">' + fmt.number(action.events) + '</td><td class="num">' +
    fmt.number(action.journeys) + '</td></tr>').join('') : ui.emptyRow(4, 'No significant actions in this window.');

  const paths = payload.paths || [];
  $('journeys-paths').innerHTML = paths.length ? paths.map((path) =>
    '<tr><td>' + fmt.escape(label(path.from)) + '</td><td>' + fmt.escape(label(path.to)) +
    '</td><td class="num">' + fmt.number(path.count) + '</td></tr>').join('')
    : ui.emptyRow(3, 'No repeated paths in this window.');

  $('journeys-events-card').hidden = !selected;
  if (selected) renderEvents(payload.events || []);
});

Admin.ready(() => $('journeys-days').addEventListener('change', Admin.refresh));
Admin.ready(() => $('journeys-user').addEventListener('change', Admin.refresh));
